简体   繁体   English

BiFunction的左右身份?

[英]Left and Right identity of a BiFunction?

When I create a Map from stream, I use:当我从 stream 创建 Map 时,我使用:

Map<Bar, Foo> fooBar = stream
    .collect(Collectors.toMap(
        Foo::getBar,
        Function.identity(),
        (x, y) -> x
    ));

The merge function I need is just the first.我需要的合并 function 只是第一个。 We have Function.identity() that we can pass as a lambda.我们有Function.identity()可以作为 lambda 传递。 Do we have something similar for BiFunction , such as BiFunction.left() ? BiFunction是否有类似的东西,例如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.) (老实说, x -> x通常也比Function.identity()更简单、更清晰。)

If you have a look at the documentation of BinaryOperator you'll find out that the only methods it defines are maxBy() and minBy() .如果您查看BinaryOperator的文档,您会发现它定义的唯一方法是maxBy()minBy() And it also inherits apply() and andThen() from BiFunction .它还从BiFunction继承了apply()andThen()

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:如果你觉得你真的需要这样的方法left()你可以扩展BinaryOperator并定义一个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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