Tuesday, April 15, 2014

Making reusable Java 8 Lambda Functions/Filters


You can create a function with parameters using Lambda in Java 8 to reduce duplicate code.
Then you can create a predicate using that function allowing you to use it as a filter for stream() allowing you to re-use your new function any number of times.This way you don't need to make a different predicate for age == 12 or age == 21.


Function< Integer, Predicate< Person >> agefunction = (age) -> person -> person.age == age;
 
private List< Person > getPeopleOfAge(final List< Person > people, final int testAge)
    {
       
        Predicate< Person > ageFilter = agefunction.apply(testAge);
        return people.stream().filter(ageFilter).collect(Collectors.toList());
    }