2

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");}
     });
}
Lutzi
  • 416
  • 2
  • 13
JavaBuilder
  • 149
  • 9

2 Answers2

6

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.

ernest_k
  • 44,416
  • 5
  • 53
  • 99
1

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.

Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97
  • We dont need myFilter(Person p) method explicitly here. You can pass lambda directly printConditionally8(persons, p-> p.age > 18); – JavaBuilder Jan 29 '20 at 06:37
  • 1
    Of course you can, but it've assumed that the question is about a difficulty to grasp a concept of method inference that's why I've provided an example like this – Mark Bramnik Jan 29 '20 at 06:43