Java BinaryOperator 和工厂方法。如何给return第一个参数?

Java BinaryOperator and factory method. How to return the first parameter?

我试图通过下一个代码将我的流转换为地图:

Collectors.toMap(City::key, Function.identity(), (first, second) -> first)

我关于最后一个 lambda 的问题。

(first, second) -> first

我经常需要获取 any 元素或总是 first 元素,如果发生碰撞。 我明白了,那已经是简短明了的形式了。但还是。对于 Function class,我们有工厂方法 Function.identity(),其中 returns 按原样传递参数。我们有 BiFunctionBinaryOperator 的工厂方法吗?或者可能接近 Function.identity()。 我也知道 BinaryOperator.minBy()BinaryOperator.maxBy(),但它们比 Function.identity().

“冗长” 并且方法不那么清晰

您可以轻松声明自己的方法:

public class BinaryOperators {
    
    public static <T> BinaryOperator<T> first() {
        return (first, second) -> first;
    }

    public static <T> BinaryOperator<T> second() {
        return (first, second) -> second;
    }

    public static <T> BinaryOperator<T> any() {
        return (first, second) -> ThreadLocalRandom.current().nextBoolean() ? first : second;
    }

}

然后在您的代码中使用它们:

Collectors.toMap(City::key, Function.identity(), BinaryOperators.first())

使用静态导入:

Collectors.toMap(City::key, identity(), first())

或者不用理会上面的代码而使用 (a, b) -> a:

toMap(City::key, identity(), (a, b) -> a))

非常清晰简洁,IMO