Stream and filter one list based on another list

I have a list of objects. These objects have a string variable. I also have a list of strings.

So something like this.

List<A> listA;

class A {

String x;

}
List<String> listB;

What I want to do is stream and filter listA, based on whether x contains any of the string objects in list B.

Is this doable?

+4
source share
3 answers
List<A> filtered = 
    listA.stream()
         .filter(a -> listB.stream().anyMatch(b -> x.a.contains(b)))
         .collect(Collectors.toList());
+3
source

Of course - just call containsin a sentence filter:

List<A> filtered = 
    listA.stream().filter(a -> listB.contains(a.x)).collect(Collectors.toList());
+1
source

HashSet String. HashSet O(1) . O(n), , (.contains) .

, :

List<A> listA ...
Set<String> setB = new HashSet<>(); // populate setB
List<A> filteredA =
    listA.stream()
        .filter(a -> setB.contains(a.x)).collect(toList());

Also see this answer for some specific evidence of performance differences.

+1
source

Source: https://habr.com/ru/post/1678200/


All Articles