在讲解Map排序之前,我们先来稍微了解下map。map是键值对的集合接口,它的实现类主要包括:HashMap,TreeMap,Hashtable以及LinkedHashMap。其中这四者的区别如下(简单介绍):
TreeMap默认是升序的,如果我们需要改变排序方式,则需要使用比较器:Comparator。
Comparator可以对集合对象或者数组进行排序的比较器接口,实现该接口的public compare(T o1,T o2)方法即可实现排序,该方法主要是根据第一个参数o1小于、等于或者大于o2分别返回负整数、0或者正整数。如下:
import java.util.*;
public class TreeMapTest {
public static void main(String[] args) {
Map<String,String> map = new TreeMap<String, String>(
new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o2.compareTo(o1);
}
}
);
map.put("a","aaaa");
map.put("b","bbbb");
map.put("d","dddd");
map.put("c","cccc");
Set<String> keySet = map.keySet();
Iterator<String> iter = keySet.iterator();
while (iter.hasNext()){
String key = iter.next();
System.out.println(key + ":" + map.get(key));
}
}
}
运行结果如下:
d:dddd
c:cccc
b:bbbb
a:aaaa
上面例子是对根据TreeMap的key来进行排序的,但是有时我们需要根据TreeMap的value来进行排序。对value排序我们就需要借助于Collections的sort(List
方法,该方法根据指定比较器产生的顺序对指定列表进行排序。但是有一个前提条件,那就是所有的元素都必须能够根据所提供的比较器来进行比较。如下:
import java.util.*;
public class TreeMapTest {
public static void main(String[] args) {
Map map = new TreeMap();
map.put("d", 15);
map.put("b", 34);
map.put("a", 111);
map.put("c", 53);
//这里将map.entrySet()转换成list
List> list = new ArrayList>(map.entrySet());
//然后通过比较器来实现排序
Collections.sort(list,new Comparator>() {
//升序排序
public int compare(Map.Entry o1,
Map.Entry o2) {
return o1.getValue() - o2.getValue();
}
});
for(Map.Entry mapping:list){
System.out.println(mapping.getKey()+":"+ mapping.getValue());
}
}
}
运行结果:
d:15
b:34
c:53
a:111
我们都知道HashMap的值是没有顺序的,它是按照key的HashCode来实现的。对于这个无序的HashMap我们要怎么来实现排序呢?参照TreeMap的value排序,我们一样的也可以实现HashMap的排序。
import java.util.*;
public class HashMapTest {
public static void main(String[] args) {
Map map = new HashMap();
map.put("a",100);
map.put("b",1000);
map.put("c",1);
map.put("d",10);
List> list = new ArrayList>(map.entrySet());
Collections.sort(list, new Comparator>() {
//升序排列
public int compare(Map.Entry o1, Map.Entry o2) {
return o1.getValue() - o2.getValue();
}
});
for (Map.Entry mapping: list){
System.out.println(mapping.getKey()+":" + mapping.getValue());
}
}
}
运行结果:
c:1
d:10
a:100
b:1000