[英]Set of String with Stream to HashMap in Java 8
How do I create HashMap of String and List of String out of Set of String with Stream? 如何使用Stream创建字符串的字符串和字符串列表的HashMap?
Set<String> mySet;
Map<String, List<String>> = mySet.stream().map(string -> {
// string will be my key
// I have here codes that return List<String>
// what to return here?
}).collect(Collectors.toMap(.....)); // what codes needed here?
Thank you. 谢谢。
You don't need the map()
step. 您不需要
map()
步骤。 The logic that produces a List<String>
from a String
should be passed to Collectors.toMap()
: 从
String
生成List<String>
的逻辑应该传递给Collectors.toMap()
:
Map<String, List<String>> map =
mySet.stream()
.collect(Collectors.toMap(Function.identity(),
string -> {
// put logic that returns List<String> here
}));
The map
operation is useless here, because you don't want to change the string itself, or you would have to map
it to an Entry<String, List<String>>
and then collect them, but this is not easier. 这里的
map
操作没用,因为你不想更改字符串本身,或者你必须将它map
到Entry<String, List<String>>
然后收集它们,但这并不容易。
Instead just build the map, the string as key and get your codes
as values : 相反,只需构建地图,将字符串作为键,并将
codes
作为值:
Map<String, List<String>> map =
mySet.stream().collect(Collectors.toMap(str->str, str-> getCodesFromStr(str));
If you want to know, how it would be with a map
operation and use Entry
(a pair) : 如果你想知道,如何使用
map
操作并使用Entry
(一对):
Map<String, List<String>> = mySet.stream().map(str->
new AbstractMap.SimpleEntry<String,List<String>>(str, getCodesFromStr(str))
).collect(Collectors.toMap(Entry::getKey, Entry::getValue));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.