天天看点

map集合根据key或者value进行排序

jdk1.8版本

public static List<String> sortMapByValue(Map<String, Integer> map) {
        int size = map.size();
        //通过map.entrySet()将map转换为"1.B.1.e=78"形式的list集合
        List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(size);
        list.addAll(map.entrySet());
        List<String> keys = list.stream()
                .sorted(Comparator.comparing(Map.Entry<String, Integer>::getValue).reversed())
                .map(Map.Entry<String, Integer>::getKey)
                .collect(Collectors.toList());
        return keys;
    }
           

1.8版本之前

public static <K,V> extends Comparator<? Super V> Map<K,V> sortByValue(Map<K,V> map){
	List<Map.Entry<K,V>> list = new LinkedList<Map.Entry<K,V>>(map.entry());
	Collections.sort(list, new Comparator<Map.Entry<K,V>>(){
		@Override
		public int compare(Map.Entry<K,V> o1, Map.Entry<K,V> o2){
			int compare = (o1.getValue()).compareTo(o2.getValue());
			return -compare;
		}
	});
	Map<K,V> result = new LinkedHashMap<K,V>;
	for (Map.Entry<K,V> entry : list){
		result.put(entry.getKey(), entry.getValue());
	}
	return result;
}
           

测试

public static void main(String[] args) {
        //这里自定义一个需要排序的map集合
        Map<String, Integer> map = new HashMap<String, Integer>();
        map.put("1.B.1.a", 45);
        map.put("1.B.1.e", 65);
        map.put("1.B.1.c", 12);
        map.put("1.B.1.b", 15);
        map.put("1.B.1.d", 78);
        List<String> keys = sortMapByValue(map);
        keys.forEach(System.out::println);
    }