मैं एक तुलनित्र लिखना चाहता हूं जो मुझे डिफ़ॉल्ट प्राकृतिक आदेश के बजाय ट्रीपैप को मूल्य के आधार पर क्रमबद्ध करने देगा।
मैंने ऐसा कुछ करने की कोशिश की, लेकिन पता नहीं चल सका कि क्या गलत हुआ:
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तुलनित्र से पास हो सकता हूं ?