![](/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.