k88 k88 - 6 months ago 24x
Java Question

Comparing two collections using Stream - anyMatch

I want to compare if any of the objects in a

is present in a

I could iterate over both lists and compare all elements using
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()));

When I do this I constantly get
, even when I'd expect a
. 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);