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
  • 46,063
  • 13
  • 87
  • 137
dev7ba
  • 103
  • 3

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
  • 374,785
  • 51
  • 663
  • 734
  • 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
  • 46,063
  • 13
  • 87
  • 137
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
  • 110,516
  • 12
  • 173
  • 277