BinaryOperator 的标识

我在 Java8 中的 UnaryOperator Interface 中看到以下一段代码,该代码对参数不执行任何操作并返回相同的值。


static <T> UnaryOperator<T> identity() {

    return t -> t;

}

BinaryOperator 有什么东西可以接受两个相同类型的参数并返回一个值


static <T> BinaryOperator<T> identity() {

    return (t,t) -> t;

}

为什么我问这个问题是为了满足以下要求,


List<String> list = Arrays.asList("Abcd","Abcd");

Map<String,Integer> map = list.stream().collect(Collectors.toMap(str->str, 

str->(Integer)str.length(),(t1,t2)->t1));

System.out.println(map.size());

在上面的代码中,我不想对相同键的两个值做任何事情,我只想返回一个值,因为在我的情况下,值肯定是相同的。由于我不使用T2值声纳抛出的错误,所以我找出是否有像任何事物UnaryOperator.identity()用于BinaryOpertor也java8


吃鸡游戏
浏览 283回答 3
3回答

哔哔one

你的问题真的没有意义。如果您将建议的BinaryOperator.identity方法粘贴到 IDE 中,您会立即看到它会抱怨标识符t被声明了两次。为了解决这个问题,我们需要为每个参数使用不同的标识符:return&nbsp;(t,&nbsp;u)&nbsp;->&nbsp;t;现在我们可以清楚地看到这不是一个恒等函数。这是一个接受两个参数并返回第一个参数的方法。因此,最好的名字应该是这样的getFirst。回答您关于 JDK 中是否有类似内容的问题:no。使用标识函数是一个常见的用例,因此为此定义一个方法很有用。任意返回两个的第一个参数不是一个常见的用例,并且有一个方法来做到这一点是没有用的。

摇曳的蔷薇

T意味着它们具有相同的类型,而不是相同的值,这本身就不是一个身份。,它只是手段BinaryOperator将被用于相同类型,但是提供identity了不同的值......这在某种程度上听起来像foldLeft或foldRight或者foldLeftIdentity/foldRightIdentity,没有哪个Java。

三国纷争

您的代码似乎可以改进为List<String> list = Arrays.asList("Abcd", "Abcd");Map<String, Integer> map = list.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toMap(Function.identity(), String::length, (a, b) -> a));System.out.println(map.size());或者可能对于您的用例,我不想对相同键的两个值做任何事情,我只想返回一个值,您可以选择在使用实现时随机返回任何值,如下所示:private static <T> BinaryOperator<T> any() {&nbsp; &nbsp; return Math.random() < 0.5 ? ((x, y) -> x) : ((x, y) -> y);}然后在您的代码中将其用作Map<String, Integer> map = list.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toMap(Function.identity(), String::length, any()));多亏了 Holger、Eugene 和 Federico 的建议,该any方法还有其他有效的实现可以实际涉及使用:private static <T> BinaryOperator<T> any() {&nbsp; &nbsp; // suggested by Holger&nbsp; &nbsp; return ThreadLocalRandom.current().nextBoolean() ? ((x, y) -> x) : ((x, y) -> y);&nbsp; &nbsp; // suggested by Eugene&nbsp; &nbsp; long nt = System.nanoTime();&nbsp;&nbsp; &nbsp; ((nt >>> 32) ^ nt) > 0 ? ((x, y) -> x) : ((x, y) -> y);}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java