Java – is there a way to compare two lists with streaming media?

I have a class named MyClass, which contains several members, one of which is mystring:

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

Now, I have a set of MyClass and another set of string

My question is:

How do I compare these two collections with streaming media? Is that possible?

Solution

You can map the MyClass list to the string list and compare them normally:

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

You can also concatenate all the elements in the list into a string and compare them directly This is only valid if the order of the elements in both lists is the same The following examples:

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));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>