mcfly soft mcfly soft - 2 months ago 6
Java Question

How to apply OR filters to a java.util.stream?

I have a

List
:

List<String> mylist=Arrays.asList("Abla","Tbla","Cbla");


I have 2 filters prepared for my stream:

Predicate<String> startswith_A= s-> s.startsWith("A");
Predicate<String> startswith_T= s-> s.startsWith("T");


Following example filters for "A":

mylist.stream().filter(startswith_A).forEach(mystring -> {
System.out.println("filtered : " + mystring);
});


How can I apply the same for a filter "A" or "T"?

Something like:

mylist.stream().filter(startswith_A || startswith_T).forEach(mystring -> {
System.out.println("filtered : " + mystring);
});


I don't want to create a new predicate like:

Predicate<String> startswith_A_or_T= s-> s.startsWith("T") || s.startsWith("A");


How can I do this with 2 seperate
Predicate
s?

Answer

You could simply use .or between the 2 Predicates:

mylist.stream().filter(startswith_A.or(startswith_T)).forEach(mystring -> {
    System.out.println("filtered : " + mystring);
});

Result:

filtered : Abla
filtered : Tbla