Reputation: 11665
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 ?
Upvotes: 2
Views: 88
Reputation: 393996
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;
Upvotes: 4
Reputation: 32028
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
Upvotes: 2