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

如何将嵌套的Java集合中的所有项目展平为单个List?

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

如何将嵌套的Java集合中的所有项目展平为单个List?

假设您使用 Java 8 ,那么可以

StreamAPI
通过以下方法
flatMap(Function<? super T,? extends Stream<? extends R>>mapper)
来实现:

// 1. Convert the Set as a Stream of List<Map<String, List<Object>>>// 2. Extract the elements of the lists to get a Stream of Map<String, List<Object>>// 3. Extract values of the maps to get a Stream of List<Object>// 4. Extract the elements of the lists to get a Stream of Object// 5. Get rid of duplicates// 6. Collect the result as a List of ObjectList<Object> result = complexNestedCollection.stream()    .flatMap(List::stream)    .flatMap(m -> m.values().stream())    .flatMap(List::stream)    .distinct()    .collect(Collectors.toList());

<R> Stream<R> flatMap(Function<? super T,? extends Stream<? extends R>>mapper)

返回一个流,该流包括将流中的每个元素替换为通过将提供的映射函数应用于每个元素而生成的映射流的内容而得到的结果。将每个映射流的内容放入该流后,将其关闭。(如果映射的流为null,则使用空流。)


对于 以前的版本

Java
,你仍然可以使用
FluentIterable

谷歌番石榴 更换
Stream
和使用
transformAndConcat(Function<? super E,? extendsIterable<? extends T>>function)
,而不是
flatMap
扁平化您的收藏。

然后,先前的代码段将被重写为下一个:

List<Object> result =    new ArrayList<>(        new linkedHashSet<>( FluentIterable.from(complexNestedCollection)     .transformAndConcat(         new Function<List<Map<String, List<Object>>>, Iterable<Map<String, List<Object>>>> () {  public Iterable<Map<String, List<Object>>> apply(final List<Map<String, List<Object>>> input) {      return input;  }         }     ).transformAndConcat(         new Function<Map<String, List<Object>>, Iterable<List<Object>>> () {  public Iterable<List<Object>> apply(final Map<String, List<Object>> input) {      return input.values();  }         }     ).transformAndConcat(         new Function<List<Object>, Iterable<Object>> () {  public Iterable<Object> apply(final List<Object> input) {      return input;  }         }     ).toList()        )    );


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

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

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