Skip to content

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();

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");
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

Java 8: I am trying like,

 List resultList = reponseIds.parallelStream.filter()

Expected result:

Result -  ["xyz:one/first/same"



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 =
      .map(item ->"/")))

    List<String> result = -> {
      // 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);

Runnable example: