Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java stream API: map field without getter syntax

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());
like image 569
gavenkoa Avatar asked Jan 29 '15 19:01

gavenkoa


1 Answers

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);
like image 108
Lii Avatar answered Sep 21 '22 22:09

Lii