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

问题描述

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

In my project, I have taken a HashMap like this

假设我有:

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

排序的HashMap应该是:

Sorted HashMap Should be :

我该怎么做?

推荐答案

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; .如何排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 19:40