Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use :: operator as this reference [duplicate]

Converting a list of objects Foo having an id, to a Map<Integer,Foo> with that id as key, is easy using the stream API:

public class Foo{
    private Integer id;
    private ....
    getters and setters...
}

Map<Integer,Foo> myMap = 
fooList.stream().collect(Collectors.toMap(Foo::getId, (foo) -> foo));

Is there any way to substitute the lambda expression: (foo) -> foo with something using the :: operator? Something like Foo::this

like image 344
dev7ba Avatar asked Oct 10 '17 08:10

dev7ba


3 Answers

While it's not a method reference, Function.identity() is what you need:

Map<Integer,Foo> myMap = 
    fooList.stream().collect(Collectors.toMap(Foo::getId, Function.identity()));
like image 186
Eran Avatar answered Oct 17 '22 14:10

Eran


You can use the Function.identity() to replace a foo -> foo lambda.


If you really want to demostrate a method reference, you can write a meaningless method

class Util {
    public static <T> T identity(T t) { return t; }
}

and refer to it by the method reference Util::identity:

( ... ).stream().collect(Collectors.toMap(Foo::getId, Util::identity));
like image 43
Andrew Tobilko Avatar answered Oct 17 '22 14:10

Andrew Tobilko


There is a difference between Function.identity() and x -> x as very good explained here, but sometimes I favor the second; it's less verbose and when the pipeline is complicate I tend to use: x -> x

like image 20
Eugene Avatar answered Oct 17 '22 16:10

Eugene