使用Stream比较两个集合-anyMatch [英] Comparing two collections using Stream - anyMatch
问题描述
我想比较list1
中是否存在list2
中的任何对象.
我可以遍历两个列表并使用.contains()
比较所有元素,但我想知道是否没有更有效的方法.我发现了此,我正在尝试实施建议的方法:
List<Item> list1;
List<Item> list2;
boolean anyMatch = list1.stream().anyMatch(x -> x.equals(list2.stream()));
System.out.println(anyMatch);
执行此操作时,即使我希望使用true
,我也总是得到false
.怎么会来?
根据您的评论,您有两个列表,分别为list1
和list2
.您想确定list1
中是否至少包含list2
中的一个元素.
使用Stream API,您可以获得list2
的Stream
.然后,调用 anyMatch(predicate)
返回此流的元素之一是否与给定谓词匹配,在这种情况下,该谓词将测试该元素是否包含在list1
中.
boolean anyMatch = list2.stream().anyMatch(list1::contains);
这使用方法参考作为谓词. /p>
通过将list1
转换为Set
,可以保证恒定的查找时间,从而获得更好的性能:
boolean anyMatch = list2.stream().anyMatch(new HashSet<>(list1)::contains);
I want to compare if any of the objects in a list2
is present in a list1
.
I could iterate over both lists and compare all elements using .contains()
but I am wondering if there is not a more efficient way. I found this and I am trying to implement the suggested method:
List<Item> list1;
List<Item> list2;
boolean anyMatch = list1.stream().anyMatch(x -> x.equals(list2.stream()));
System.out.println(anyMatch);
When I do this I constantly get false
, even when I'd expect a true
. How come?
From your comments, you have two lists, list1
and list2
. You want to find out if at least one of the element in list2
is contained in list1
.
With the Stream API, you can acquire a Stream
of list2
. Then, a call anyMatch(predicate)
returns whether one of the element of this stream matches the given predicate, which, in this case, tests whether the element is contained in list1
.
boolean anyMatch = list2.stream().anyMatch(list1::contains);
This uses a method reference as the predicate.
You would have better performance by converting the list1
into a Set
, which guarantees constant-time look-up:
boolean anyMatch = list2.stream().anyMatch(new HashSet<>(list1)::contains);
这篇关于使用Stream比较两个集合-anyMatch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!