Java8组键映射
我想按键对贴图对象进行分组。我尝试使用此代码,但出现编译错误:Java8组键映射,java,lambda,java-8,grouping,collectors,Java,Lambda,Java 8,Grouping,Collectors,我想按键对贴图对象进行分组。我尝试使用此代码,但出现编译错误: Non-static method cannot be referenced from a static context 我的代码: Map<String, List<A>> getAMap() { return Arrays.stream(SomeArray.values()) .map(map -> createObject())
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;
}
看起来您的代码在某些级别上是错误的,而错误消息并不是实际发生的情况 例如,
createObject()
返回一个Map
,因此您会得到一个流
,显然.collector.groupingBy(Map.Entry::getKey…
将无法工作。您需要稍微更改代码才能工作:
Arrays.stream(someArray)
.flatMap(map -> createObject().entrySet().stream())
.collect(Collectors.groupingBy(Entry::getKey,
Collectors.mapping(Entry::getValue, Collectors.toList())));
SomeArray.values()
?可能是SomeEnum
?能否显示调用getAMap()
的位置。错误消息表明您从静态方法(可能是main
?)调用它,而没有对象引用。请选中此项:。createObject()
返回一个映射
,您正在尝试使用属于映射项的方法。关于错误消息,请考虑…
Arrays.stream(someArray)
.flatMap(map -> createObject().entrySet().stream())
.collect(Collectors.groupingBy(Entry::getKey,
Collectors.mapping(Entry::getValue, Collectors.toList())));