.flatMap() 或 .collect() 是否可以均匀地多个集合 [英] Is it possible to .flatMap() or .collect() evenly multiple collections

查看:23
本文介绍了.flatMap() 或 .collect() 是否可以均匀地多个集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如有集合 [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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆