java HashMap排序< String,Integer> .如何排序? [英] java HashMap sorting <String,Integer> . How to sort it?

查看:320
本文介绍了java HashMap排序< String,Integer> .如何排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
如何对地图进行排序<键,值> Java中的值?

Possible Duplicate:
How to sort a Map<Key, Value> on the values in Java?

在我的项目中,我采用了这样的HashMap

In my project, I have taken a HashMap like this

HashMap等级=新的HashMap();

假设我有:

degree.put("a",5);
degree.put("b",2);
degree.put("c",4);
degree.put("d",2);
degree.put("e",3);
degree.put("f",5);

现在我必须根据给定的Integer值对该列表进行排序

Now I have to Sort this list according to given Integer values

排序的HashMap应该是:

Sorted HashMap Should be :

{a = 5,f = 5,c = 4,e = 4,b = 4,d = 2}

我该怎么做?

推荐答案

HashMap无序集合.它没有排序顺序.甚至TreeMap也会按键而不是值进行排序.

A HashMap is an unordered collection. It has no sort order. Even a TreeMap will sort by key, not value.

如果要按值的排序顺序准备排序列表,则必须创建一个适当的对象(例如ArrayList<Map.Entry<String,Integer>>),遍历HashMap并插入所有条目,然后使用整理功能调用Collections.sort.

If you want to prepare a sorted list by the sort order of the values, you'll have to create an appropriate object, such as an ArrayList<Map.Entry<String,Integer>>, iterate over your HashMap and insert all the entries, and then call Collections.sort with a collation function.

这篇关于java HashMap排序&lt; String,Integer&gt; .如何排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆