如何在地图上交换密钥? [英] how to swap key in map?
问题描述
有没有办法排序存储在字符串变量中的数字?
is there a way to sort this numbers stored in a string variable?
TreeMap< String,List< QBFElement>> qbfElementMap = new TreeMap< String,List< QBFElement>>();
这是键的地图:
27525-1813,
27525-3989,
27525-4083,
27525-4670,
27525-4911,
27526-558,
27526-1303,
27526-3641,
27526-4102,
27527-683,
27527-2411,
27527-4342
这是键和值的列表对于每个关键是一个列表。
现在,我如何按数字升序排序这个键。
this is the list of keys and the value for each of the key is a list.
now, how can i sort this key in ascending order by number.
ex。如果我想排序:1,2,11,20,31,3,10
i想要具有的输出是:1,2,3,10,11,20,31
但是当我使用treemap的autosort时,输出结果如下:1,10,11,2,20,3,31
ex. if i want to sort : 1,2,11,20,31,3,10
i want to have as output is : 1,2,3,10,11,20,31
but when i use the autosort of treemap the output goes : 1,10,11,2,20,3,31
我如何以升序排序按数字排序?
how can i sort it in ascending order by numeric?
,语言是java :)谢谢:)
and the language is java :) thank you:)
推荐答案
地图中的键不是整数
,而是 String
值。这就是为什么密钥按照观察次序进行排序。
The keys in your map are not Integer
but String
values. That's why the key's are sorted like observed.
将地图更改为
TreeMap<Long,List<QBFElement>> qbfElementMap
或创建一个专门的比较器
这将为 String
类型键提供预期的数字顺序。
or create it with a specialized Comparator
that will provide the expected numerical order for the String
type keys.
从String值到Longs的映射可以这样完成:
A mapping from your String values to Longs could be done like this:
private Long convertToLongTypeKey(String key) {
String[] parts = key.split("-");
// next lines assumes, that the second part is in range 0...9999
return Long.parseLong(parts[0]) * 10000 + Long.parseLong(parts[1]);
}
Comparator< String>
可以使用相同的映射来创建两个基于String的键的数值比较:
An implementation of Comparator<String>
could use the same mapping to create a numerical comparision of two String based keys:
new TreeMap<String,List<QBFElement>>(new Comparator<String>(){
@Override
public int compare(String key1, String key2) {
String[] parts1 = key1.split("-");
Long long1 = Long.parseLong(parts1[0]) * 10000 + Long.parseLong(parts1[1]);
String[] parts2 = key2.split("-");
Long long2 = Long.parseLong(parts2[0]) * 10000 + Long.parseLong(parts2[1]);
return long1.compareTo(long2);
}
});
这篇关于如何在地图上交换密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!