nimo23
nimo23

Reputation: 5680

Java8 StreamFilter within List

I have something like this:

   // common code without java8-closures/stream-api (this works):
    public static List<Person> getFilteredRes_OLD(List<Person>all, List<String> names){

    List<Person> pos = new ArrayList<>();

    for(Person e: all){
        for(String n: names){
            if(Person.isFemale(n).test(e)){
                pos.add(e);
            }
        }

    }

    return pos;
}

public static Predicate<Person> isFemale(String test) {
    return p -> p.getFirstName()!=null && p.getFirstName().equalsIgnoreCase(test);
}

Now, I want to use the new Stream-filter API in Java 8:

   // JAVA 8 code (this works, but only for a specified filter-value):

    public static List<Person> getFilteredRes_NEW(List<Person>all, List<String> names){

    return all.stream()
    // how can I put the list 'names" into the filter-Method
    // I do not want to test only for 'Lisa' but for the wohle "names"-list
    .filter( Person.isFemale("Lisa") )
    .collect(Collectors.<Person>toList());

    return pos;
}

My Question for getFilteredRes_NEW() is:

How can I put the list of 'names" into the filter-Method? I do not want to test only for 'Lisa' but for the wohle "names"-list within the stream.

Upvotes: 0

Views: 148

Answers (1)

JB Nizet
JB Nizet

Reputation: 691755

Here's, I think, the filter instruction you want:

.filter(person -> names.stream().anyMatch(
                      name -> Person.isFemale(name).test(person)))

For each person, it tests if there is at least one name N in the list of names for which the Person.isFemale(N).test(P) returns true.

It would be much simpler, and create less instances of Predicate, if you simply had a method

public boolean isFemale(Person p, String name) {
    return p.getFirstName() != null && p.getFirstName().equalsIgnoreCase(test);
}

The code would become

.filter(person -> names.stream().anyMatch(name -> isFemale(person, name)))

You should also rename isFemale(), because it doesn't test at all if the person is female. It tests if a person has a given first name (ignoring the case).

Upvotes: 3

Related Questions