Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 Predicates?

like image 583
mcfly soft Avatar asked Feb 07 '23 00:02

mcfly soft


1 Answers

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
like image 162
Unheilig Avatar answered Feb 08 '23 14:02

Unheilig