Java 8组按键图
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()
returns一个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())));
我想按键对地图对象进行分组。我尝试使用此代码,但出现编译错误:
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()
returns一个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())));