Daneel S. Yaitskov Daneel S. Yaitskov - 1 year ago 90
Java Question

Lambda reference to a field

I'd like to know how to get lambda reference to a field.
I don't want to use a method because my field is public final.
I suspect this is impossible but I don't see an obvious statement.

class A {
public final String id;

Map<String, A> f(List<A> l) {
return l.stream().collect(Collectors.toMap(A::id, Function.identity()));

Answer Source

You can always use a lambda expression:

return l.stream().collect(Collectors.toMap(a -> a.id, Function.identity()));

I think that "method references" are called this way for a reason, and therefore apply only for methods.