如何打印出 HashMap<String, String> 的内容根据其值升序排列? [英] How print out the contents of a HashMap<String, String> in ascending order based on its values?
问题描述
我有这个 HashMap
我需要根据其中包含的 values 以升序打印出来(不是钥匙).
I have this HashMap
that I need to print out in ascending order according to the values contained in it (not the keys).
但是我打印出来的顺序似乎是随机的.
But the order when I print it out is seemingly random.
以升序打印出来的最佳方式是什么?
What's the best way to print it out in ascending value order?
Map<String, String> codes = new HashMap<String, String>();
codes.put("A1", "Aania");
codes.put("X1", "Abatha");
codes.put("C1", "Acathan");
codes.put("S1", "Adreenas");
换句话说,上面的例子应该是这样打印出来的:
In other words, the example above should print out as this:
A1, Aania
X1, Abatha
C1, Acathan
S1, Adreenas
推荐答案
您无法仅从 HashMap 类中做到这一点.
You aren't going to be able to do this from the HashMap class alone.
我会使用 Map<String, String>代码
,构造TreeMap
您将 codes
Map 的值映射到键(这将要求您的原始 Map 具有从键到值的一对一映射).由于 TreeMap 提供了迭代器,它以升序键顺序返回条目,这将为您提供您想要的顺序(按值排序)的第一个映射的值/键组合.
I would take the Map<String, String> codes
, construct a reverse map of TreeMap<String, String> reversedMap
where you map the values of the codes
Map to the keys (this would require your original Map to have a one-to-one mapping from key-to-value). Since the TreeMap provides Iterators which returns entries in ascending key order, this will give you the value/key combination of the first map in the order (sorted by values) you desire.
Map<String, String> reversedMap = new TreeMap<String, String>(codes);
//then you just access the reversedMap however you like...
for (Map.Entry entry : reversedMap.entrySet()) {
System.out.println(entry.getKey() + ", " + entry.getValue());
}
有几个集合库(commons-collections、Google Collections 等)具有类似的双向 Map 实现.
There are several collections libraries (commons-collections, Google Collections, etc) which have similar bidirectional Map implementations.
这篇关于如何打印出 HashMap<String, String> 的内容根据其值升序排列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!