기본 자연 순서 대신 TreeMap을 값으로 정렬 할 수있는 비교기를 작성하고 싶습니다.
나는 이런 식으로 시도했지만 무엇이 잘못되었는지 알 수 없다 :
import java.util.*;
class treeMap {
public static void main(String[] args) {
System.out.println("the main");
byValue cmp = new byValue();
Map<String, Integer> map = new TreeMap<String, Integer>(cmp);
map.put("de",10);
map.put("ab", 20);
map.put("a",5);
for (Map.Entry<String,Integer> pair: map.entrySet()) {
System.out.println(pair.getKey()+":"+pair.getValue());
}
}
}
class byValue implements Comparator<Map.Entry<String,Integer>> {
public int compare(Map.Entry<String,Integer> e1, Map.Entry<String,Integer> e2) {
if (e1.getValue() < e2.getValue()){
return 1;
} else if (e1.getValue() == e2.getValue()) {
return 0;
} else {
return -1;
}
}
}
나는 내가 무엇을 요구하는지 추측한다 : 나는 Map.Entry비교기에 전달할 수 있습니까 ?