实现Map按值排序

馋奶兔 提交于 2020-08-05 23:37:08

Map按照值排序,需要自定义比较器,实现Comparator接口,实现compare方法。

public class SortByVlue {
	public static void main(String[] args) {
		Map<String, Long> map = new HashMap<String, Long>();
		map.put("e", null);
		map.put("a", 4L);
		map.put("b", 2L);
		map.put("d", 3L);
		map.put("c", 1L);
		map.put("f", null);
		// 默认会根据键排序
		for (Entry<String, Long> entry : map.entrySet()) {
			System.out.println(entry.getKey() + ": " + entry.getValue());
		}
		System.out.println("....................");
		Map<String, Long> result = sortMapByValue(map);
		System.out.println("Map排序前:");
		for (Entry<String, Long> entry : result.entrySet()) {
			System.out.println(entry.getKey() + ": " + entry.getValue());
		}
	}

	public static Map<String, Long> sortMapByValue(Map<String, Long> map) {
		int count = 0;
		// 存放结果
		Map<String, Long> sortMap = new LinkedHashMap<String, Long>();
		// 封装,对list排序
		List<Entry<String, Long>> list = new ArrayList<Map.Entry<String, Long>>();
		// 在排序前计算value为null的个数
		for (Entry<String, Long> entry : map.entrySet()) {
			if (entry.getValue() != null) {
				list.add(entry);
			} else {
				count++;
			}
		}
		System.out.println("value=null的个数:" + count);
		Collections.sort(list, new ValueComparator());
		//使用迭代器进行遍历
		Iterator<Entry<String, Long>> iterator = list.iterator();
		while (iterator.hasNext()) {
			Entry<String, Long> next = iterator.next();
			sortMap.put(next.getKey(), next.getValue());
		}

		return sortMap;
	}
}
class ValueComparator implements Comparator<Entry<String, Long>> {

	@Override
	public int compare(Entry<String, Long> o1, Entry<String, Long> o2) {
		// 值比较器
		return o1.getValue().compareTo(o2.getValue());
	}
}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!