【发布时间】:2017-03-02 01:35:57
【问题描述】:
我是 java8 流的新手,很抱歉这个愚蠢的问题。这是我的代码,我正在尝试创建 id & value 的映射,但我收到此错误,无法修复。谁能帮助我有什么替代方法?
public static Map<Integer, String> findIdMaxValue(){
Map<Integer, Map<String, Integer>> attrIdAttrValueCountMap = new HashMap<>();
Map<Integer, String> attrIdMaxValueMap = new HashMap<>();
attrIdAttrValueCountMap.forEach((attrId, attrValueCountMap) -> {
attrValueCountMap.entrySet().stream().sorted(this::compareAttrValueCountEntry).findFirst().ifPresent(e -> {
attrIdMaxValueMap.put(attrId, e.getKey());
});
});
}
及排序方法
public static int compareAttrValueCountEntry(Map.Entry<String, Integer> e1, Map.Entry<String, Integer> e2) {
int diff = e1.getValue() - e2.getValue();
if (diff != 0) {
return -diff;
}
return e1.getKey().compareTo(e2.getKey());
}
我收到了这个错误
"Cannot use this in a static context"
【问题讨论】:
-
尝试使用实际的类名而不是
this。 -
我明白了,那么解决方案是什么?我正在尝试迭代地图并尝试对其进行排序 attrValueCountMap.entrySet().stream().sorted(this::compareAttrValueCountEntry)
标签: java java-8 java-stream