Why the reference to the Java method of the instance method cannot be assigned to the user interface

Here is my code:

public class SearchByLambda {

     private Map<String,Consumer<Person>> searchCritertiaHolder = new HashMap<String,Consumer<Person>>();

     private static final String AGED = "aged";

     public SearchByLambda(){
           searchCritertiaHolder.put(AGED, (Person p)-> {p.filterAgedPerson(p);} );
     }

     private Consumer<Person> getFilter(String personType){
          return searchCritertiaHolder.get(personType);
     }

     public static void main(String[] args) {
          SearchByLambda searchUsage = new SearchByLambda();
          Person p = new Person(59,"shailesh");
          Person p1 = new Person(58,"ganesh");

          searchUsage.getFilter(AGED).accept(p);
          searchUsage.getFilter(AGED).accept(p1);

          Person.printAgedPersons();
     }
 }

 class Person{

       private static List<Person> agedPersons = new ArrayList<>();

       private int age;

       private String name;

       public int getAge() {
              return age;
       }

       public void setAge(int age) {
          this.age = age;
       }

       public String getName() {
            return name;
       }

       public void setName(String name) {
            this.name = name;
       }

       public Person(int age,String name){
           this.age = age;
           this.name = name;
       }

       public void filterAgedPerson(Person person){
          if(person.getAge() > 58){
              agedPersons.add(person);
          }
       }

       public static void printAgedPersons(){
            for(Person person : agedPersons){
                System.out.println(person.getName());
            }
       }
 }

When I replace the following Lambda expression

     searchCritertiaHolder.put(AGED, (Person p)-> {p.filterAgedPerson(p);});

from

              searchCritertiaHolder.put(AGED, Person::filterAgedPerson);

this gives me a compilation error. I am using java 8 and compiling through eclipse. Why is this so? Why can't I assign a method reference for an instance method of any arbitrary object to a consumer functional interface?

+4
source share
1 answer

Your definition filterAgedPersontakes an argument Person, although this is not a static method. This is not necessary, and it should not, if you want to use it as Consumer<Person>. What you are finishing is compatible with BiConsumer<Person, Person>.

: "" , this.

- filterAgedPerson, Person

   public void filterAgedPerson() {
      if (this.getAge() > 58) {
          agedPersons.add(person);
      }
   }

, Predicate<Person> Consumer<Person> . .

+6

Source: https://habr.com/ru/post/1612163/


All Articles