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
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()));
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));
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With