gpt4 book ai didi

java - 如何在 Java8 中将一个流缩减为另一个流?

转载 作者:行者123 更新时间:2023-11-30 06:14:11 25 4
gpt4 key购买 nike

例如,我想像这样创建无限的十位组流:

0=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1=[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
2=[20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
...

我想使用无限的整数流作为输入,然后应该对其进行分组。如果第一个流迭代 10 次,则结果流应该只迭代一次。

我的工作但不是很优雅的代码如下所示:

// create a stream from 0 (inclusive) to 100 (exclusive)
IntStream.iterate(0, i -> i+1).boxed().limit(100)

// slow down
.peek((i) -> {try {Thread.sleep(50);} catch (InterruptedException e) {}})

// group by tens
/* ugly: */.collect(Collectors.groupingBy(i -> i / 10)).entrySet()
/* not working: */ //.makeSequentialGroups(i -> i / 10)

// print to console
.forEach(System.out::println);

如何在不必收集和重新流式传输的情况下对 int 流进行分组? (如果可能甚至不用装箱)

最佳答案

此类功能在我的 StreamEx 中可用库并称为 groupRuns :您可以根据提供的谓词将相邻元素收集到中间列表中。示例:

IntStreamEx.iterate(0, i -> i+1).boxed().limit(100)
.peek((i) -> {try {Thread.sleep(50);} catch (InterruptedException e) {}})
.groupRuns((a, b) -> a/10 == b/10)
.forEach(System.out::println);

关于java - 如何在 Java8 中将一个流缩减为另一个流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30681805/

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