Search code examples
javalambdajava-8java-streamfunctional-interface

Using streams with custom functional interfaces


I have just started looking at streams on this Oracle website. One question which immediately came to me looking at code like the one below is: what if I want to reuse the filter logic, e.g. having a method "isAdult" in Person?

This won't work in streams as a method reference as it does not accept a parameter Person. Analogously I would not be able to create a filter which accepts and additional int parameter with an age to create a parameterisable "isOlderThan" logic.

I could not find a way to use streams in conjunction with custom functional interfaces. How would you model such behaviour? It feels to me like creating a static "isAdult" method in the above scenario is not a very clean solution and neither is creating a "PersonChecker" object with such methods.

List<Person> list = roster.parallelStream().filter((p) -> p.getAge() > 18).collect(Collectors.toList()); 

Thank you


Solution

  • List<Person> list = roster.parallelStream().filter((p) -> p.getAge() > 18).collect(Collectors.toList());
    

    what if I want to reuse the filter logic, e.g. having a method "isAdult" in Person?

    List<Person> list = roster.parallelStream().filter(Person::isAdult).collect(Collectors.toList());
    

    or

    List<Person> list = roster.parallelStream().filter(p -> p.isAdult()).collect(Collectors.toList());
    

    I would not be able to create a filter which accepts and additional int parameter with an age to create a parameterisable "isOlderThan" logic.

    List<Person> list = roster.parallelStream().filter(p -> p.isOlderThan(18)).collect(Collectors.toList());
    

    I don't see what custom functional interfaces have to do with your question. Predicate is the only functional interface you need here, and lambdas and method references are extremely easy way to create instances of Predicate.