简体   繁体   中英

Left and Right identity of a BiFunction?

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.

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.)

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()
    ));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM