Skip to content
Advertisement

Java 8 stream string manipulation and comparison [closed]

In Java 8, can I use streams to manipulate, filter and compare string? I know how to do in java 5 but stuck with Java 8 api using Streams. Please assist with Java 8

Let us assume I have two Java objects (Request and Response) as below

public class Request {
   
     List<String> requestIds;

     requestIds = new ArralyList();
     requestIds.add("xyz:one/first/same");
     requestIds.add("zzz:five/match/same");
     requestIds.add("xyz:different/second/different");
 }

public class Response {
     List<Item> responseIds;
     responseIds = new ArralyList();
     Item one = new Item("xyz:ten/first/same");
     Item two = new Item("zzz:three/match/same");
     Item three = new Item("xyz:one/third/second");
     responseIds.add(one);
     responseIds.add(two);
     responseIds.add(three);
 }
public class Item {
  String id;
}


  

I need to compare the request and response list objects as below

From request List I need extract indexOf first “/” for each list entry (for example “/first/same”) and compare this string with Response list to see which contains or not. If contains add it to result list.

Java 5 Impl:

   List result = new ArrayList();
   for(String requestString:requestIds){
   String extractedRequestString = requestString.subString(requestString.indexOf("/"));
   for(int i=0;i<responseIds.length;i++) {
      String responseString = responseIds.get(i).getId();
      if (responseString.equals(extractedRequestString)) {
          // If condition true, Adding request I'd value to result ArrayList
              result.add(requestString);
        }
   }
 }

Java 8: I am trying like,

 List resultList = reponseIds.parallelStream.filter()

Expected result:

Result -  ["xyz:one/first/same"
          "zzz:five/match/same"]

Advertisement

Answer

Your code looks broken to me. Based on your “Java 5 Impl” logic I will assume responseIds should be:…

Update: According to your comment both the request and response need to id.substring(id.indexOf("/"));

Given that assumption you could do:

    // Transforming ids here to avoid doing it for each element in requestIds
    List<String> stringResponseIds = responseIds.stream()
      .map(item -> item.id.substring(item.id.indexOf("/")))
      .collect(Collectors.toList());

    List<String> result = requestIds.stream().filter(id -> {
      // extracting here instead of using `map` to avoid loosing the complete string
      String extractedRequestString = id.substring(id.indexOf("/"));
      // A simple contains now that responses are Strings.
      return stringResponseIds.contains(extractedRequestString);
    }).collect(Collectors.toList());

Runnable example: https://replit.com/@lrn2prgrm/StreamStringMatching#Main.java

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement