有时候我们业务上需要对map里面的值按照key的大小来进行排序的时候我们就可以利用如下方法来进行排序了,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
package test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class Demo {
private HashMap<Integer, Object> map = new HashMap<Integer, Object>();
private Set<Integer> keySet = map.keySet();
public Object get(Integer key) {
return map.get(key);
}
public void put(Integer key, Object value) {
map.put(key, value);
}
@SuppressWarnings ( "unchecked" )
public void sort() {
List<Integer> list = new ArrayList<Integer>(map.keySet());
Collections.sort(list, new Comparator<Object>(){
public int compare(Object a, Object b) {
return a.toString().toLowerCase().compareTo(b.toString().toLowerCase());
}
});
this .keySet = new TreeSet<Integer>(list);
}
public Set<Integer> keySet() {
return this .key
}
public static void main(String [] args){
Demo map= new Demo();
map.put( 11 , "加" );
map.put( 12 , "关" );
map.put( 13 , "注" );
map.put( 10 , "添" );
map.put( 1 , "小" );
map.put( 8 , "记" );
map.put( 9 , "得" );
map.put( 7 , "客" );
map.put( 5 , "的" );
map.put( 6 , "博" );
map.put( 4 , "豆" );
map.put( 3 , "糖" );
map.put( 2 , "小" );
System.out.println( "排序前" );
for (Iterator it =map.keySet().iterator();it.hasNext();){
Integer key= (Integer)it.next();
System.out.println( "key[ " + key + "], value[ " + map.get(key) + "] " );
}
//
System.out.println( "排序后" );
System.out.println( "\n " );
map.sort();
for (Iterator it=map.keySet().iterator();it.hasNext();) {
Integer key=(Integer)it.next();
System.out.println( "key[ " + key + "], value[ " + map.get(key) + "] " );
}
}
}
|
运行效果如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
排序前
key[ 1 ], value[ 小]
key[ 2 ], value[ 小]
key[ 3 ], value[ 糖]
key[ 4 ], value[ 豆]
key[ 5 ], value[ 的]
key[ 6 ], value[ 博]
key[ 7 ], value[ 客]
key[ 8 ], value[ 记]
key[ 9 ], value[ 得]
key[ 10 ], value[ 添]
key[ 11 ], value[ 加]
key[ 12 ], value[ 关]
key[ 13 ], value[ 注]
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
排序后
key[ 1 ], value[ 小]
key[ 2 ], value[ 小]
key[ 3 ], value[ 糖]
key[ 4 ], value[ 豆]
key[ 5 ], value[ 的]
key[ 6 ], value[ 博]
key[ 7 ], value[ 客]
key[ 8 ], value[ 记]
key[ 9 ], value[ 得]
key[ 10 ], value[ 添]
key[ 11 ], value[ 加]
key[ 12 ], value[ 关]
key[ 13 ], value[ 注]
|
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
原文链接:http://blog.csdn.net/baidu_23086307/article/details/53140364