是否可以将.flatMap()或.collect()均匀地分布在多个集合中 [英] Is it possible to .flatMap() or .collect() evenly multiple collections
问题描述
例如,有集合 [1,2,3,4,5]
, [6,7,8]
, [9,0]
。有任何方法可以避免循环使用迭代器通过Java 8流API交错这些集合以获得以下结果 - [1,6,9,2,7,0,3,8,4,5]
?
For instance there are collections [1,2,3,4,5]
, [6,7,8]
, [9,0]
. Any way to avoid loops with iterators to interleave these collections via Java 8 stream API to get the following result - [1,6,9,2,7,0,3,8,4,5]
?
推荐答案
我不确定Stream API是否有更简单的方法,但你可以做这使用了要考虑的所有列表的索引的流:
I am not sure if there's a simpler way with the Stream API, but you can do this using a stream over the indices of all the lists to consider:
static <T> List<T> interleave(List<List<T>> lists) {
int maxSize = lists.stream().mapToInt(List::size).max().orElse(0);
return IntStream.range(0, maxSize)
.boxed()
.flatMap(i -> lists.stream().filter(l -> i < l.size()).map(l -> l.get(i)))
.collect(Collectors.toList());
}
这将获得给定列表中最大列表的大小。对于每个索引,然后将其平面映射为由该索引处的每个列表的元素形成的流(如果元素存在)。
This gets the size of the greatest list in the given lists. For each index, it then flat maps it with a stream formed by the elements of each list at that index (if the element exist).
然后您可以将其与
public static void main(String[] args) {
List<Integer> list1 = Arrays.asList(1,2,3,4,5);
List<Integer> list2 = Arrays.asList(6,7,8);
List<Integer> list3 = Arrays.asList(9,0);
System.out.println(interleave(Arrays.asList(list1, list2, list3))); // [1, 6, 9, 2, 7, 0, 3, 8, 4, 5]
}
使用 protonpack 库,你可以使用方法 interleave
这样做:
Using the protonpack library, you can use the method interleave
to do just that:
List<Stream<Integer>> lists = Arrays.asList(list1.stream(), list2.stream(), list3.stream());
List<Integer> result = StreamUtils.interleave(Selectors.roundRobin(), lists).collect(Collectors.toList());
System.out.println(result);
这篇关于是否可以将.flatMap()或.collect()均匀地分布在多个集合中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!