Hasholef
Hasholef

Reputation: 753

Is there a way of comparing two Lists with streaming?

I have a class called MyClass that contains couple of members and one of them is myString:

public class MyClass{
  //...
  private String myString;
}

Now, I have a collection of MyClass and another collection of String.

My question is:

How to compare those two collections with streaming? Is that possible?

Upvotes: 3

Views: 10491

Answers (1)

Marlon Bernardes
Marlon Bernardes

Reputation: 13853

You could map a list of MyClass to a List of Strings and then compare them normally:

List<String> anotherList = listOfMyClass.stream()
      .map(MyClass::getMyString)  //Assuming that you have a getter for myString
      .collect(Collectors.toList()); 

You could also join all the elements of the list in a single String and compare them directly. This will only work if the order of the elements should be the same in both lists. Examples below:

    final String joinSeparator = ", ";

    String firstResult = stringList
            .stream()
            .collect(Collectors.joining(joinSeparator));

    String secondResult = myClassList
            .stream()
            .map(MyClass::getMyString)
            .collect(Collectors.joining(joinSeparator));

    //Just compare them using equals:
    System.out.println(firstResult.equals(secondResult));

Upvotes: 7

Related Questions