9

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

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
dev7ba
  • 203
  • 1
  • 4

3 Answers3

7

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()));
Eran
  • 387,369
  • 54
  • 702
  • 768
  • Thanks a lot, i've tried to find and aswer without success, but it seems to be a duplicate answer. – dev7ba Oct 25 '17 at 09:50
6

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));
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
4

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

Eugene
  • 117,005
  • 15
  • 201
  • 306