Split stream into substreams with N elements

早过忘川 提交于 2020-06-16 21:15:45

问题


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)

splitting by two streams solution is correct only for 2 streams, the same for N streams will be very ugly and write-only.


回答1:


You can't split a Stream into 2 or more Streass 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());

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.



来源:https://stackoverflow.com/questions/41127391/split-stream-into-substreams-with-n-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!