栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Stream reduce()要求到底包含什么?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Stream reduce()要求到底包含什么?

让我举两个例子。首先,身份被破坏:

int result = Stream.of(1, 2, 3, 4, 5, 6)        .parallel()        .reduce(10, (a, b) -> a + b);System.out.println(result); // 81 on my run

基本上,您已经违反了以下规则:

The identity value must be an identity for the accumulatorfunction. This means that for all u, accumulator(identity, u) is equal to u

或更简单地说,让我们看看该规则是否适用于Stream中的一些随机数据:

 Integer identity = 10; BinaryOperator<Integer> combiner = (x, y) -> x + y; boolean identityRespected = combiner.apply(identity, 1) == 1; System.out.println(identityRespected); // prints false

第二个例子:

private static int howMany(List<String> tokens) {    return tokens.stream() .parallel() .reduce(0, // identity         (i, s) -> { // accumulator  return s.length() + i;         }, (left, right) -> { // combiner  return left + right + left; // notice the extra left here         });}

然后使用以下命令调用它:

List<String> left = Arrays.asList("aa", "bbb", "cccc", "ddddd", "eeeeee");List<String> right = Arrays.asList("aa", "bbb", "cccc", "ddddd", "eeeeee", "");System.out.println(howMany(left));  // 38 on my runSystem.out.println(howMany(right)); // 50 on my run

基本上,您已经违反了此规则:

Additionally, the combiner function must be compatible with theaccumulator function
或在代码中:

// this must hold!// combiner.apply(u, accumulator.apply(identity, t)) == accumulator.apply(u, t)Integer identity = 0;String t = "aa";Integer u = 3; // "bbb"BiFunction<Integer, String, Integer> accumulator = (Integer i, String s) -> i + s.length();BinaryOperator<Integer> combiner = (left, right) -> left + right + left;int first = accumulator.apply(identity, t); // 2int second = combiner.apply(u, first); // 3 + 2 + 3 = 8Integer shouldBe8 = accumulator.apply(u, t);System.out.println(shouldBe8 == second); // false


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/453007.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号