我有一门这样的课;
class: {
id: "",
sub: [{
type: 1,
value: ""
}]
}
现在,我希望组类首先由id;
class.stream().collect(Collectors.groupingBy(class::id))
然后我需要一个List<String>
的平面子值,我有以下内容:
class.stream().collect(Collectors.groupingBy(class::id,
Collectors.mapping(e ->
e.sub().stream()
.filter(v -> v.type().equals(1))
.map(sub::value),
Collectors.toList()
)))
它返回一个Map<String, List<List<String>>>
那么,如何使用Java 8函数式API将Map<String, List<List<String>>>
转换为Map<String, List<String>>
呢?
3条答案
按热度按时间h43kikqp1#
要使用Java 8函数API将Map〈String,List〉转换为Map〈String,List〉,可以使用flatMap方法沿着Stream和Collectors.toMap()。
下面是一个例子:
在本例中,我们首先使用entrySet()方法获取Map.Entry〈String,List〉流。然后使用Collectors.toMap()方法创建新的Map〈String,List〉。
Collectors.toMap()的第一个参数指定如何从原始Map中Map键,我们只需使用Map.Entry::getKey从条目中获取键。第二个参数指定如何从原始Map中Map值。
对于原始map中的每个条目,我们使用entry.getValue().stream()获取所有内部列表的流。然后使用flatMap(Collection::stream)将每个内部列表扁平化为单个String流。最后,使用Collectors.toList()将所有String元素收集到一个新列表中。
8zzbczxx2#
您可以使用
Map
收集器按键分组并合并值。示例(Java 14及以上):
输出:
relj7zay3#
就像@Sametcey建议的那样,你可以使用
flatMap
。无论何时你遇到使用嵌套列表的东西(就像你的
Map<String, List<List>>
,但是可以在更深的层次上使用它,比如Map<String, List<List<List>>>
),flatMap
都会帮助你。它会将您的流转换为单个扁平流。换句话说:一个你可以访问和操作的列表。