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

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

问题描述

<块引用>

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

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

<块引用>

HashMap 度数 = new HashMap();

假设我有:

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

<块引用>

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

排序后的 HashMap 应该是:

<块引用>

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

我该怎么做?

解决方案

一个 HashMap 是一个 无序 集合.它没有排序顺序.即使是 TreeMap 也会按键排序,而不是按值排序.

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

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

In my project, I have taken a HashMap like this

HashMap degree = new HashMap();

Suppose I have:

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

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

Sorted HashMap Should be :

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

How I can do this ?

解决方案

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

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天全站免登陆