[英]Java 8 group map by key
我想按鍵對地圖對象進行分組。 我嘗試使用此代碼,但出現編譯錯誤:
Non-static method cannot be referenced from a static context
我的代碼:
Map<String, List<A>> getAMap() {
return Arrays.stream(SomeArray.values())
.map(map -> createObject())
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
}
private Map<String, A> createObject()
final A a = new A(some attributes);
Map<String, A> map = new LinkedHashMap<>();
map.put(some key, a);
.... // add another values.
return map;
}
我需要類似的東西
{
"a", {a1, a2, a3},
"b", {a4, a5, a6},
}
看起來您的代碼在某些級別上是錯誤的,並且該錯誤消息並非確切發生的情況。
例如, createObject()
返回一個Map
因此您得到Stream<Map<...>>
,因此顯然.collect(Collectors.groupingBy(Map.Entry::getKey...
將不起作用。您需要更改代碼一點點的工作:
Arrays.stream(someArray)
.flatMap(map -> createObject().entrySet().stream())
.collect(Collectors.groupingBy(Entry::getKey,
Collectors.mapping(Entry::getValue, Collectors.toList())));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.