<分区>
我有一个多图 Map<T,List<L>> map
我需要一个包含 map 中所有值的列表,即 List<L>
.与 map.values()
我得到一个List<List<L>>
,但这不是我想要的。
有人知道没有循环的干净解决方案吗?
标签 java list dictionary
<分区>
我有一个多图 Map<T,List<L>> map
我需要一个包含 map 中所有值的列表,即 List<L>
.与 map.values()
我得到一个List<List<L>>
,但这不是我想要的。
有人知道没有循环的干净解决方案吗?
最佳答案
如果您使用的是 Java 8,您可以收集所有 L
来自所有 List<L>
的值s 在单个 List<L>
通过 Stream#flatMap
:
final List<L> list = map
// get a Collection<List<L>>
.values()
// make a stream from the collection
.stream()
// turn each List<L> into a Stream<L> and merge these streams
.flatMap(List::stream)
// accumulate the result into a List
.collect(Collectors.toList());
否则,一个 for-each
使用 Collection#addAll
的方法可以应用:
final List<L> list = new ArrayList<>();
for (final List<L> values : map.values()) {
list.addAll(values);
}
关于java - 如何将 Map<T,List<L>> 映射中的值添加到 List<L>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47182923/