由于Map中的TreeMap只能按key排序,本文中实现了通过Collections工具类及comparator接口实现Map按value排序
package me;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* 将Map中的Entry按照value的降序排序
*
* @author:TuGh,WangM
*/
public class TreeMapTest {
public static void main(String[] args) {
Map<Integer,Double> map =new LinkedHashMap<Integer,Double>();
map.put(5, 100.0);
map.put(1, 2.0);
map.put(2, 5.0);
map.put(3, 2.0);
map.put(4, 4.0);
System.out.println(map.entrySet());
List<Map.Entry<Integer, Double>> list = new ArrayList<Map.Entry<Integer, Double>>(map.entrySet());
//使用Collections工具类对list进行排序
Collections.sort(list, new Comparator<Map.Entry<Integer, Double>>() {
@Override
public int compare(Entry<Integer, Double> o1, Entry<Integer, Double> o2) {
// TODO Auto-generated method stub
//按Entry里面的value降序排序
return o2.getValue().compareTo(o1.getValue());
//按Entry里面的value升序排序
//return o1.getValue().compareTo(o2.getValue());
}
});
/**
*将按value排好序的Entry放入map中
**/
map = null;
map = new LinkedHashMap<Integer, Double>();
for(Map.Entry<Integer, Double> temp:list){
map.put(temp.getKey(), temp.getValue());
}
System.out.println(map.entrySet());
}
}