给定对象的复杂嵌套集合,例如:
Set<List<Map<String, List<Object>>>> complexNestedCollection;
是否存在通用方法来对此进行平坦化并获取其中包含List
的所有Object
s中的一个?
一些细节:
List<List<Object>>
,外部List包含其自身作为成员。(感谢AdrianJałoszewski在下面的评论中提及此内容)。注意:实际用例是从中获取所有String List<List<String>>
,这可以通过两个循环轻松完成,但是这让我对一般情况感到疑惑。
假设您使用Java 8,那么可以Stream API
通过以下方法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 Object
List<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,? extends Iterable<? 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()
)
);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句