本文介绍了如何在Java8中将流减少到另一个流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为一个例子,我想创建一个像这样十几组的无限流:

As an example, I want to create an infinite stream of Groups of tens like this:

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]
...

我想使用inifinte的int作为输入流,然后将其分组。如果第一个流迭代10次,结果流应该只迭代一次。

I want to use an inifinte stream of ints as an Input, which should then be grouped. If the first stream iterates 10 times the resulting stream should have iterated only once.

我的工作但非常优雅的代码如下所示:

My working, but not very elegant code looks like this:

// 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流组,而不必收集和重新流? (如果可能的话,甚至不必使用拳击)

How do I make groups of an int stream, without having to collect and re-stream? (If possible even without having to use boxing)

推荐答案

我的库,名为:您可以根据提供的谓词将相邻元素收集到中间列表中。示例:

Such feature is available in my StreamEx library and called groupRuns: you can collect adjacent elements into the intermediate List based on supplied predicate. Example:

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);

这篇关于如何在Java8中将流减少到另一个流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 02:29