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());
    }





    2 comments:

    Matty K said...

    I'm way out of touch with Java, and have never seen Java 8 or its Lambda stuff. Is `age -> person -> person.age==age` a way of currying?

    Here's my interpretation of your code:

    1. start with a two-parameter lambda function: `(a,b) -> a==b`
    2. curry it
    3. apply a←testAge, effectively resulting in: `(b) -> testAge==b`
    4. pass the resulting (partially applied) lambda to .filter

    Is that right?

    Spikeles said...

    Sorry Matty, didn't see your comment till just now. Yes I believe it is what you say, had to look up that term, hadn't seen it before.

    http://java-success.blogspot.com.au/2014/05/java-8-currying-tutorial.html