我有List<List<String>>
。我想根据内部列表的特定元素将其转换为 Map。
我试过了
ddList.stream().flatMap(x -> x.stream()
.collect(Collectors.toMap(Function.identity(), String::length)));
它不工作。这里出了什么问题?
它应该是:
Map<String, Integer> sMap =
ddMap.stream()
.flatMap(x -> x.stream())
.collect(Collectors.toMap(Function.identity(),
String::length));
PS如果输入List
s包含任何重复元素,此代码将抛出异常。您可以使用以下方法消除重复项distinct
:
Map<String, Integer> sMap =
ddMap.stream()
.flatMap(x -> x.stream())
.distinct()
.collect(Collectors.toMap(Function.identity(),
String::length));
编辑:
根据您的评论,您根本不需要flatMap
,而是这样的:
Map<String, List<String>> sMap =
ddMap.stream()
.collect(Collectors.toMap(l -> l.get(0), // or some other member
// of the inner List
Function.identity()));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句