TreeMap按照value进行排序
- public class Testing {
- public static void main(String[] args) {
- HashMap<String,Double> map = new HashMap<String,Double>();
- ValueComparator bvc = new ValueComparator(map);
- TreeMap<String,Double> sorted_map = new TreeMap<String,Double>(bvc);
- map.put("A",99.5);
- map.put("B",67.4);
- map.put("C",67.4);
- map.put("D",67.3);
- System.out.println("unsorted map: "+map);
- sorted_map.putAll(map);
- System.out.println("results: "+sorted_map);
- }
- }
- class ValueComparator implements Comparator<String> {
- Map<String, Double> base;
- public ValueComparator(Map<String, Double> base) {
- this.base = base;
- }
- // Note: this comparator imposes orderings that are inconsistent with equals.
- public int compare(String a, String b) {
- if (base.get(a) >= base.get(b)) {
- return -1;
- } else {
- return 1;
- } // returning 0 would merge keys
- }
- }
- public class MapUtil
- {
- public static <K, V extends Comparable<? super V>> Map<K, V>
- sortByValue( Map<K, V> map )
- {
- List<Map.Entry<K, V>> list =
- new LinkedList<Map.Entry<K, V>>( map.entrySet() );
- Collections.sort( list, new Comparator<Map.Entry<K, V>>()
- {
- public int compare( Map.Entry<K, V> o1, Map.Entry<K, V> o2 )
- {
- return (o1.getValue()).compareTo( o2.getValue() );
- }
- } );
- Map<K, V> result = new LinkedHashMap<K, V>();
- for (Map.Entry<K, V> entry : list)
- {
- result.put( entry.getKey(), entry.getValue() );
- }
- return result;
- }
- }
如果想对Map<String, List<String>> 进行排序,如下;
public static <K, V extends Comparable<? super V>> Map<K, List<String>> sortByValue(Map<K, List<String>> map, final int i) {
List<Map.Entry<K, List<String>>> list = new LinkedList<Map.Entry<K, List<String>>>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<K, List<String>>>() {
public int compare(Map.Entry<K, List<String>> o1, Map.Entry<K, List<String>> o2) {
String key1 = o1.getValue().get(i);
String key2 = o2.getValue().get(i);
return (key1).compareTo(key2);
}
});
Map<K, List<String>> result = new LinkedHashMap<K, List<String>>();
for (Map.Entry<K, List<String>> entry : list) {
result.put(entry.getKey(), entry.getValue());
}
return result;
}
测试:
public static void main(String[] args) {
Map<String, List<String>> map = new HashMap<String, List<String>>();
List<String> list1 = new ArrayList<String>();
List<String> list2 = new ArrayList<String>();
List<String> list3 = new ArrayList<String>();
list1.add("aa");
list1.add("aa");
list1.add("aa");
list2.add("dbb");
list2.add("axxa");
list2.add("e");
list3.add("cc");
list3.add("axxa");
list3.add("xx");
map.put("a", list1);
map.put("b", list3);
map.put("d", list2);
map = sortByValue(map, 2);
Set<String> key = map.keySet();
for(Iterator<String> iter = key.iterator();iter.hasNext();) {
String kk = iter.next();
List<String> value = map.get(kk);
System.out.println( kk +" =" + value);
}
}
结果:
a =[aa, aa, aa]
d =[dbb, axxa, e]
b =[cc, axxa, xx]
这样,可封装在一个方法中,方便调用,避免因多个此类数据排序而导致更多类冗余。