1

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

0

1 Answer 1

3
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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, and apologies for the trivial question, it arose from an unrelated misunderstanding of the method references (i tried using p::isAdult), combined with the erroneous idea that since the Predicate "test" method accepts 1 parameter, so must by lambda.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.