使用N个元素将流拆分为子流 [英] Split stream into substreams with N elements
问题描述
在Java中,我们可以将流分成不超过N个元素的子流吗? 例如
Can we somehow split stream into substreams with no more than N elements in Java? For example
Stream<Integer> s = Stream.of(1,2,3,4,5);
Stream<Stream<Integer>> separated = split(s, 2);
// after that separated should contain stream(1,2), stream(3,4), stream(5)
通过两个流拆分解决方案仅对2个流正确,对于N个流,这将是非常丑陋且只写的.
splitting by two streams solution is correct only for 2 streams, the same for N streams will be very ugly and write-only.
推荐答案
您无法轻松直接地将Stream
分为2个或更多Streas
.程序化的唯一方法是由夫妇将元素收集到List
并将它们再次映射回Stream
:
You can't split a Stream
into 2 or more Streas
s easily and directly. The only way the procedural one consisting of collecting the elements to the List
by the couples and mapping them back to Stream
again:
Stream<Integer> s = Stream.of(1,2,3,4,5);
List<Integer> list = s.collect(Collectors.toList());
int size = list.size();
List<List<Integer>> temp = new ArrayList<>();
List<Integer> temp2 = new ArrayList<>();
int index = 0;
for (int i=0; i<size; i++) {
temp2.add(list.get(i));
if (i%2!=0) {
temp.add(temp2);
temp2 = new ArrayList<>();
}
if (i == size - 1 && size%2!=0) {
temp.add(temp2);
}
}
Stream<Stream<Integer>> stream = temp.stream().map(i -> i.stream());
如您所见,这是很漫长的路,不值得.将对存储在List
中而不是Stream
中会更好吗? java-stream API的问题不是用于数据存储,但对其进行处理.
As you see it's a really long way an not worth. Wouldn't be better to store the pairs in the List
rather than Stream
? The java-stream API is not used for data storage but their processing.
这篇关于使用N个元素将流拆分为子流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!