Java如何对HashMap按值进行排序

HashMap的值是没有顺序的,它是按照key的HashCode来实现的。对于这个无序的HashMap我们要怎么来实现排序呢?(TreeMap类似)

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;


		Map<String, Long> map = new HashMap<String, Long>();
		map.put("c", 33333L);
		map.put("a", 11111L);
		map.put("d", 44444L);
		map.put("e", 55555L);
		map.put("b", 22222L);
		
		//将map.entrySet()转换成list
		List<Map.Entry<String, Long>> list = new ArrayList<Map.Entry<String, Long>>(map.entrySet());
		Collections.sort(list, new Comparator<Map.Entry<String, Long>>() {
			//降序排序
			@Override
			public int compare(Entry<String, Long> o1, Entry<String, Long> o2) {
				//return o1.getValue().compareTo(o2.getValue());
				return o2.getValue().compareTo(o1.getValue());
			}
		});

		for (Map.Entry<String, Long> mapping : list) {
			System.out.println(mapping.getKey() + ":" + mapping.getValue());
		}

运行结果:

e:55555
d:44444
c:33333
b:22222
a:11111

    原文作者:席飞剑
    原文地址: https://blog.csdn.net/xifeijian/article/details/46522531
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞