I am trying out method reference inside forEach
private static void printConditionally8(List<Person> people, Predicate<Person> predicate) {
people.forEach(p-> { if (predicate.test(p)){
System.out.println("Print here");}
});
}
Above works fine but I want to make it more short using methods reference however its giving compilation problem.Is there any way to make it happen ?
private static void printConditionally8(List<Person> people, Predicate<Person> predicate) {
people.forEach({ if (predicate::test){
System.out.println("Print here");}
});
}
You should be able to filter the list before running your action:
people.stream().filter(predicate).forEach(p -> System.out.println("Print here"));
You can't use if(predicate::test)
because if
takes a boolean expression (the type of predicate::test
wouldn't even be known here - check lambda expressions' target typing documentation). The only way to make it work would be to invoke the test()
method as you did it in your first snippet.
I think you use the method reference concept in a wrong way.
Method reference is a nifty syntax for calling a method as if its a lambda (java 8+ will do all the conversions):
Here is an example:
public class Foo {
private static void printConditionally8(List<Person>persons, Predicate<Person> f) {
persons.stream().filter(f).forEach(p -> System.out.print(p + " is here"));
}
private static Boolean myFilter(Person p) {
return p.age > 18;
}
public static void main(String[] args) {
List<Person> persons = ... // create a list of persons
printConditionally8(persons, Foo::myFilter);
}
}
Notice how does the main method really call the printConditionally8
. It passes the reference to the method myFilter as if is an "anonymous class" - that implements the Predicate
interface.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.