在网络开发过程中客户端跟服务器经常遇到各种各样的验证方式,参数排序就是常见的方法之一,按照参数的首字母升序或者降序,参数少的话可以主观的排序就行了,但是参数多的时候肯定不能这么干了,下面介绍几个方法
0. 以Key进行排序
第一种。直接声明TreeMap这样输出的就是排序好的
Map<Integer, Person> map =
new
TreeMap<Integer, Person>();
map.put(key,vale);
|
第二种。先声明HashMap<String, Integer>();然后HashMap在转
TreeMap这样输出的就是排序好的
Map<Integer, Person> map =
new
HashMap<Integer, Person>();
TreeMap treemap =
new
TreeMap(map);
- 以Value进行排序
先声明一个HashMap对象:Map<String, Integer> map =
new
HashMap<String, Integer>();
然后我们可以将Map集合转换成List集合中,而List使用ArrayList来实现如下:
List<Entry<String,Integer>> list =
new
ArrayList<Entry<String,Integer>>(map.entrySet());
最后通过Collections.sort(List l, Comparator c)方法来进行排序,代码如下:
Collections.sort(list,
new
Comparator<Map.Entry<String, Integer>>() {
public
int
compare(Map.Entry<String, Integer> o1,
Map.Entry<String, Integer> o2) {
return
(o2.getValue() - o1.getValue());
}
});
上述代码是讲map中的value按照逆序排序,如果需要按照升序进行排序的话,只需要修改o2.getValue() - o1.getValue()为o1.getValue() - o2.getValue()即可
参考 :http://www.cnblogs.com/avivahe/p/5657071.html