Java 如何对 <Integer, MyObject> 映射进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18431580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to sort <Integer, MyObject> map
提问by grep
I have map like that:
我有这样的地图:
Map<Integer, MyEntry> map = new HashMap<Integer, MyEntry>();
MyEntry is that:
MyEntry 是这样的:
public class MyEntry {
private String title;
private String value;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
after putting values in map , I want to sort it. First element to be smallest and the last element to be biggest.
将值放入 map 后,我想对其进行排序。第一个元素最小,最后一个元素最大。
采纳答案by Jeff Storey
For sorting by key, you can use a SortedMap
- one common implementation is a TreeMap
. Since Integers have a natural sort order, you don't need to do anything special other than just put them into a TreeMap
对于按键排序,您可以使用 a SortedMap
- 一个常见的实现是 a TreeMap
。由于整数有一个自然的排序顺序,除了将它们放入一个TreeMap
If you wanted to sort by values, there are a couple of techniques described in this question Sort a Map<Key, Value> by values (Java)
如果您想按值排序,在这个问题Sort a Map<Key, Value> by values (Java) 中描述了几种技术
回答by Suresh Atta
A HashMap
does not guarantee the order after you sorted the map
. If you want sort the map by keys
, use TreeMap.
AHashMap
不保证排序后的顺序map
。如果要按 对地图进行排序keys
,请使用TreeMap。
This might helpful:Order HashMap<String,Integer> according Integer
回答by MSA
If you want to sort you can use 2 types LinkedHashMapor most used is TreeaMap .
如果你想排序,你可以使用 2 种LinkedHashMap或者最常用的是TreeaMap。
Map<Integer, MyEntry> map = new LinkedHashMap<Integer, MyEntry>();
OR
或者
Map<Integer, MyEntry> map = new TreeMap<Integer, MyEntry>();
And to add some small sample, you can use this code:
并添加一些小样本,您可以使用以下代码:
Map<Integer, String> map = new TreeMap<Integer, String>();
map.put(1, "one");
map.put(3, "three");
map.put(2, "two");
// prints one two three
for(Integer key : map.keySet()) {
System.out.println(map.get(key);
}
Some usefull:
一些有用的:
Cheers,
干杯,