![](/img/trans.png)
[英]HashMap<String,List<String>> to HashMap<Object,List<String>> using streams
[英]List of Strings to hashmap using Streams
我有一个这样的“,”分隔的字符串数组
a b c d,
f b h j,
l p o i,
我希望将其转换为类似HashMap<String, List<String>>
的Hashmap HashMap<String, List<String>>
以便列表中的第二个元素(由空格分隔成为键,第三个元素变为值),所以,这应该成为
b -> c,h
p -> o
我想使用Streams API,我认为这是可行的方法:
List<String> entries = new ArrayList<>();
HashMap<String, List<String>> map = new HashMap<>();
HashMap<String, List<String>> newMap = entries.stream()
.collect(line -> {
if (map.contains(line.split(" ")[1])) {
// Get existing list and add the element
map.get(line.split(" ")[1].add(line.split(" ")[1]));
} else {
// Create a new list and add
List<String> values = new ArrayList<>();
values.add(line.split(" ")[1]);
map.put(line.split(" ")[0], values);
}
});
有什么更好的办法吗? 我究竟应该如何从collect函数返回Hashmap?
您可以如下所示使用Collectors.groupingBy
对输入进行分组(遵循内联注释):
String[] inputs = {"a b c d,", "f b h j,", "l p o i,"};
Map<String, List<String>> results =
Arrays.stream(inputs).map(s -> s.split(" ")).//splt with space
collect(Collectors.groupingBy(arr -> arr[1], // Make second element as the key
Collectors.mapping(arr -> arr[2], // Make third element as the value
Collectors.toList())));//collect the values to List
System.out.println(results);
输出:
{p=[o], b=[c, h]}
建议您在此处阅读API ,以了解Collectors.groupingBy
和Collectors.mapping
工作方式。
您可以使用groupingBy
收集器以及Collectors.mapping
作为下游收集器来完成手头的任务。
Map<String, List<String>> collect =
myList.stream()
.map(s -> s.split(" "))
.collect(Collectors.groupingBy(a -> a[1],
Collectors.mapping(a -> a[2], Collectors.toList())));
输出:
{p=[o], b=[c, h]}
如果要维持插入顺序,则可以指定一个LinkedHashMap
如下所示:
Map<String, List<String>> collect =
myList.stream()
.map(s -> s.split(" "))
.collect(Collectors.groupingBy(s -> s[1],
LinkedHashMap::new,
Collectors.mapping(s -> s[2], Collectors.toList())));
输出:
{b=[c, h], p=[o]}
如果您需要HashMap
,而不仅仅是任何Map
HashMap<String, List<String>> output =myList.stream().map(s -> s.split(" "))
.collect(Collectors.groupingBy((s) -> s[1],
HashMap::new,
Collectors.mapping(
(s) -> s[2],
Collectors.toList())));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.