gpt4 book ai didi

java - 流<流> : flatMap vs. 减少

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:54:19 28 4
gpt4 key购买 nike

<分区>

如果我执行以下“连接”两个流的代码

  • 首先通过 flatMapping a Stream<Stream<Integer>>
  • 然后通过减少 Stream<Stream<Integer>>使用 Stream.concat()

我在这两种情况下都获得了相同的正确结果,但过滤操作的次数不同。

public class FlatMapVsReduce {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);

Predicate<Integer> predicate1 = i -> {
System.out.println("testing first condition with " + i);
return i == 3;
};

Predicate<Integer> predicate2 = i -> {
System.out.println("testing second condition with " + i);
return i == 7;
};

System.out.println("Testing with flatMap");
Integer result1 =
Stream.of(list.stream().filter(predicate1),
list.stream().filter(predicate2))
.flatMap(Function.identity())
.peek(i -> System.out.println("peeking " + i))
.findFirst()
.orElse(null);
System.out.println("result1 = " + result1);

System.out.println();
System.out.println("Testing with reduce");
Integer result2 =
Stream.of(list.stream().filter(predicate1),
list.stream().filter(predicate2))
.reduce(Stream::concat)
.orElseGet(Stream::empty)
.peek(i -> System.out.println("peeking " + i))
.findFirst()
.orElse(null);
System.out.println("result2 = " + result2);
}
}

我在两种情况下都得到了预期的结果 (3)。但是,第一个操作对集合中的每个元素应用第一个过滤器,而第二个操作在满足一个元素后立即停止。输出是:

Testing with flatMap
testing first condition with 1
testing first condition with 2
testing first condition with 3
peeking 3
testing first condition with 4
testing first condition with 5
testing first condition with 6
testing first condition with 7
testing first condition with 8
testing first condition with 9
result1 = 3

Testing with reduce
testing first condition with 1
testing first condition with 2
testing first condition with 3
peeking 3
result2 = 3

为什么两者之间存在行为差异?是否可以改进 JDK 代码以使其在第一种情况下与在第二种情况下一样高效,或者 flatMap 中是否有某些东西使其不可能?

附录:以下替代方案与使用 reduce 的替代方案一样高效,但我仍然无法解释原因:

    Integer result3 = Stream.of(predicate1, predicate2)
.flatMap(c -> list.stream().filter(c).limit(1))
.peek(i -> System.out.println("peeking " + i))
.findFirst()
.orElse(null);
System.out.println("result3 = " + result3);

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com