When I create a Map from stream, I use:
Map<Bar, Foo> fooBar = stream
.collect(Collectors.toMap(
Foo::getBar,
Function.identity(),
(x, y) -> x
));
The merge function I need is just the first. We have Function.identity()
that we can pass as a lambda. Do we have something similar for BiFunction
, such as BiFunction.left()
? External library can work as well.
CodePudding user response:
No. It's simplest, and most efficient, to do exactly what you have done. (Honestly, x -> x
is often simpler and clearer than Function.identity()
as well.)
CodePudding user response:
If you have a look at the documentation of BinaryOperator
you'll find out that the only methods it defines are maxBy()
and minBy()
. And it also inherits apply()
and andThen()
from BiFunction
.
Nothing similar to what you're looking for.
If you feel like you really need such method left()
you can extend BinaryOperator
and define one:
public interface MyBinaryOperator<T> extends BinaryOperator<T> {
static <T> BinaryOperator<T> left() {
return (left, right) -> left;
}
}
Applying to your example:
foos.stream()
.collect(Collectors.toMap(
Foo::getBar,
Function.identity(),
MyBinaryOperator.left()
));