strange syntax error using function reference

mcfly soft :

I have the following code ...

List<Person> personenListe = Arrays.asList(new Person[] {person1, person2,person3,person4});

        List<Person> personmitnamen4 = personenListe.stream().filter(p -> p.getName().equals("name4")).collect(Collectors.toList());
        personmitnamen4.forEach(p -> System.out.println(p));
        personmitnamen4.forEach(new Consumer<Person>() {
            @Override
            public void accept(Person p) {
                // TODO Auto-generated method stub
                System.out.println(p);
            }
        });
        personmitnamen4.forEach(p -> System.out::println); // <- the target type of this expression must be a functional interface.

enter image description here

My Person class has a toString method declared.

... where I sysout persons in different way. But the most preferable way to do shows me a syntax error in eclipse. In IntelliJ I do not get this . Can anyone explain or tell me what I am doing wrong here ?

Eran :

You should write either

personmitnamen4.forEach(System.out::println);

which is a method reference.

or

personmitnamen4.forEach(p -> System.out.println(p));

which is a lambda expression.

What you attempted to pass to forEach:

p -> System.out::println

is a lambda expression implementing a functional interface with a method that accepts a Person and returns a method reference compatible with Consumer<Person>, which makes the lambda expression compatible with the functional interface Function<Person,Consumer<Person>>, which is not the Consumer<Person> required by forEach.

You can test it by observing that the following would pass compilation:

Function<Person,Consumer<Person>> foo = p -> System.out::println;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=115634&siteId=1