import java.util.*;
public class treeMap {
static String key1 ="";
static Integer vlue1 ;
public static void main(String [] arg){
Map<String,Integer> map = new TreeMap<>();
map.put("1",2);
map.put("2",4);
map.put("3",5);
map.put("4",12);
map.put("5",23);
map.put("6",65);
map.put("7",1);
map.put("8",10);
Map<String , Integer> map1 = new HashMap<>();
map1 = sortMapByValue(map);
for (String key : map1.keySet()) {
key1 =key;
vlue1=map1.get(key);
System.out.println("key= "+ key + " and value= " + map1.get(key));
}
System.out.println("方位号:"+key1+"\n 距离:"+vlue1);
}
public static Map<String, Integer> sortMapByValue(Map<String, Integer> oriMap) {
class MapValueComparator implements Comparator<Map.Entry<String, Integer>> {
@Override
public int compare(Map.Entry<String, Integer> me1, Map.Entry<String, Integer> me2) {
return me1.getValue().compareTo(me2.getValue());
}
}
if (oriMap == null || oriMap.isEmpty()) {
return null;
}
Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
List<Map.Entry<String, Integer>> entryList = new ArrayList<Map.Entry<String, Integer>>(
oriMap.entrySet());
Collections.sort(entryList, new MapValueComparator());
Iterator<Map.Entry<String, Integer>> iter = entryList.iterator();
Map.Entry<String, Integer> tmpEntry = null;
while (iter.hasNext()) {
tmpEntry = iter.next();
sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
}
return sortedMap;
}
}