class Person {
public String name;
public String getName() { return name; }
}
Are there special syntax sugar for accessing fields in stream API through lambda? I see:
List<Person> persons;
persons.stream().map(Person::getName).collect(Collectors.toList());
persons.stream().map(p -> p.name).collect(Collectors.toList());
What about something like (which is not working, I know that):
persons.stream().map(Person::name).collect(Collectors.toList());
There is no method-reference-like syntax for field access. It sometimes would have been convenient if there were.
Motivation: The fact that there isn't has some justification in that it's a bit strange in Java to regard fields as methods. It would also create difficulties with overloading since a field and a method can have the same name.
Work-around: Provide a getter for the field as in the example in the question text. Or use a lambda expression instead. Something like this:
someMethod(obj -> obj.someField);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With