mat*_*boy 71 java list java-8 java-stream
我有以下情况
Map<Key, ListContainer> map;
public class ListContainer{
List<AClass> lst;
}
Run Code Online (Sandbox Code Playgroud)
我已经合并所有列表lst从ListContainer从对象Map地图.
public static void main(String args[]){
List<AClass> alltheObjectsAClass = map.values().stream(). // continue....
}
Run Code Online (Sandbox Code Playgroud)
任何想法,使用Java 8流API?
Puc*_*uce 146
我认为flatMap()这就是你要找的东西.
例如:
List<AClass> allTheObjects = map.values()
.stream()
.flatMap(listContainer -> listContainer.lst.stream())
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
Sky*_*ker 47
替代方案:Stream.concat()
Stream.concat(map.values().stream(), listContainer.lst.stream())
.collect(Collectors.toList()
Run Code Online (Sandbox Code Playgroud)
上面已经回答了,但这是您可以采取的另一种方法。我找不到我改编的原始帖子,但为了解决您的问题,这是代码。如上所述,您希望在 Java 8 中使用 flatMap() 函数。您可以将其放入实用程序类中,然后只需调用“RandomUtils.combine(list1, list2, ...);” 你会得到一个包含所有值的列表。请小心使用通配符 - 如果您想要一个不太通用的方法,您可以更改它。您还可以针对 Sets 修改它 - 您只需在 Sets 上使用 flatMap() 时要小心,以避免由于 Set 接口的性质而导致 equals/hashCode 方法丢失数据。
编辑 - 如果您对 Set 接口使用这样的通用方法,并且您碰巧使用 Lombok,请确保您了解 Lombok 如何处理 equals/hashCode 生成。
/**
* Combines multiple lists into a single list containing all elements of
* every list.
*
* @param <T> - The type of the lists.
* @param lists - The group of List implementations to combine
* @return a single List<?> containing all elements of the passed in lists.
*/
public static <T> List<?> combine(final List<?>... lists) {
return Stream.of(lists).flatMap(List::stream).collect(Collectors.toList());
}
Run Code Online (Sandbox Code Playgroud)