package com.zhilei.test;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class mapValueCompareSort {
public static void main(String[] args) {
HashMap<String, Double> mapDesc = new HashMap<String, Double>();
ValueComparator bvcDESC = new ValueComparator(mapDesc);
TreeMap<String, Double> sorted_map_Desc = new TreeMap<String, Double>(bvcDESC);
mapDesc.put("A", 99.5);
mapDesc.put("B", 67.4);
mapDesc.put("C", 67.4);
mapDesc.put("D", 67.3);
mapDesc.put("E", 11.0);
mapDesc.put("F", -0.1);
mapDesc.put("G", 0.1);
mapDesc.put("H", -99.1);
sorted_map_Desc.putAll(mapDesc);
System.out.println("降序=====results: " + sorted_map_Desc);
HashMap<String, Double> mapAsc = new HashMap<String, Double>();
ValueComparatorAsc bvcAsc = new ValueComparatorAsc(mapAsc);
TreeMap<String, Double> sorted_mapAsc = new TreeMap<String, Double>(bvcAsc);
mapAsc.put("宽", 99.5);
mapAsc.put("B", 67.4);
mapAsc.put("C", 67.4);
mapAsc.put("D", 67.3);
mapAsc.put("r", 11.0);
mapAsc.put("rt", -0.1);
mapAsc.put("ee", 0.1);
mapAsc.put("cc", -99.1);
System.out.println("升序====unsorted map: " + mapAsc);
sorted_mapAsc.putAll(mapAsc);
System.out.println("升序====results: " + sorted_mapAsc);
}
}
class ValueComparator implements Comparator<String> {
Map<String, Double> base;
public ValueComparator(Map<String, Double> base) {
this.base = base;
}
public int compare(String a, String b) {
if (base.get(a) >= base.get(b)) {
return -1;
} else {
return 1;
}
}
}
class ValueComparatorAsc implements Comparator<String> {
Map<String, Double> base;
public ValueComparatorAsc(Map<String, Double> base) {
this.base = base;
}
public int compare(String a, String b) {
if (base.get(a) <= base.get(b)) {
return -1;
} else {
return 1;
}
}
}