我们知道 HashMap不能直接排序。
TreeMap可以排序但是只能以键值对里面的key 排序,不能有value排序。
如果我们的需求恰好需要该怎么办,这里我们针对HashMap和TreeMap有一种通用的方法,我们可以把他转换成list,通过操作list进行排序就行了。当然HashMap也可以转换为TreeMap进行以Key排序,但是TreeMap依旧不能直接以value排序,所以这里不做介绍。
以HashMap转换为list,并以value排序举例,TreeMap同理,只要换个名字就行。
代码奉上:
/*
* HashMap转换为List 并以value进行排序
*/
public class Collection_21_MapToList {
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] args) {
//hashmap排序 认真看,转set再转list
int i =1;
Map<String,Integer> map =new HashMap<String,Integer>();
map.put("a", 1);
map.put("c", 2);
map.put("d", 1);
map.put("b", 12);
//因为map中存储的是entry,所以想要把map转换为list,那么list中的元素应该为Entry类型
//先把entry拿出来
Set set =map.entrySet();
//调用ArrayList的有参构造 把set转换为list
List<Entry<String,Integer>> list =new ArrayList<Entry<String,Integer>>(set);
Collections.sort(list,new Comparator<Entry<String, Integer>>() {
@Override
public int compare(Entry<String, Integer> o1,Entry<String, Integer> o2) {
return o1.getValue() - o2.getValue();
}
});
System.out.println(list);
}
}