假设您使用 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() ) );


