栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

.flatMap()或.collect()是否可以平均多个集合

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

.flatMap()或.collect()是否可以平均多个集合

我不确定Stream API是否有更简单的方法,但是您可以在所有列表的索引上使用流来考虑以下问题:

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

这将获得给定列表中最大列表的大小。然后,对于每个索引,它使用该列表中每个列表的元素在该索引处形成的流(如果该元素存在的话)进行平面映射。

然后,您可以将其与

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
来做到这一点:

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/498374.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号