如何打印出HashMap的内容< String,String>基于其值的升序? [英] How print out the contents of a HashMap<String, String> in ascending order based on its values?
问题描述
我有这个 但我打印出来的顺序看起来是随机的。 b 以 升序价格顺序打印出来的最佳方式 HashMap
,需要按照其中包含的 值升序打印出来( 不是键 )。
$ b
Map< String,String> codes = new HashMap< String,String>();
codes.put(A1,Aania);
codes.put(X1,Abatha);
codes.put(C1,Acathan);
codes.put(S1,Adreenas);
换句话说,上面的例子应该打印出来:
A1,Aania
X1,Abatha
C1,Acathan
S1,Adreenas
您无法单独从HashMap类中完成此操作。
我会将地图< String,String>代码
,构造一个反向映射 TreeMap< String,String> invertMap
在那里你映射代码
映射到键的值(这将要求你的原始Map有一个一对一的映射键到值)。由于TreeMap提供的迭代器按照递增的键顺序返回条目,因此这会给你按照你想要的顺序(按值排序)的第一个映射的值/键组合。
地图< String,String> invertMap = new TreeMap< String,String>(codes);
//然后你只需访问反向映射,不过你喜欢...
for(Map.Entry entry:reversedMap.entrySet()){
System.out.println( entry.getKey()+,+ entry.getValue());
}
有几个集合库(commons-collections,Google Collections等)具有类似的双向Map实现。
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
You aren't going to be able to do this from the HashMap class alone.
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());
}
There are several collections libraries (commons-collections, Google Collections, etc) which have similar bidirectional Map implementations.
这篇关于如何打印出HashMap的内容< String,String>基于其值的升序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!