Java 有没有办法用流比较两个列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24864219/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a way of comparing two Lists with streaming?
提问by Hasholef
I have a class called MyClass
that contains couple of members and one of them is myString
:
我有一个名为的类MyClass
,其中包含几个成员,其中一个是myString
:
public class MyClass{
//...
private String myString;
}
Now, I have a collection of MyClass
and another collection of String
.
现在,我有一个集合MyClass
和另一个集合String
。
My question is:
我的问题是:
How to compare those two collections with streaming? Is that possible?
如何将这两个集合与流媒体进行比较?那可能吗?
采纳答案by Marlon Bernardes
You could map a list of MyClass
to a List of Strings and then compare them normally:
您可以将一个列表映射MyClass
到一个字符串列表,然后正常比较它们:
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:
您还可以将列表中的所有元素合并成一个String
并直接进行比较。这仅在两个列表中元素的顺序应该相同时才有效。下面的例子:
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));