简体   繁体   中英

strange syntax error using function reference

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.

在此处输入图片说明

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 ?

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;

You should either use lambda or use method reference , not both at the same time.

personmitnamen4.forEach(System.out::println); // method reference

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM