如何通过key或者value值对map排序?这是在Stackoverflow网站问的比较普遍的一个问题。在这里我们将给你一个处理方案。
顺序不能保证
最常用的map类型是HashMap,官方的api明确指出“
makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time”意思是插入数据的顺序随着时间的推移并不是一直不变的。
LinkedHashMap 维持的插入的顺序
当你使用EntrySet集合存储数据时候,它通常使用LinkedHashMap来保证顺利一致性,官方文档有一句话“
it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order)” ,但是仍旧没有提供方法或者处理方式来对整个实体进行排序。
TreeMap 是通过key排序
TreeMap默认是通过key对插入的entry进行排序,官方api指出“
The map is sorted according to the natural ordering of its keys, or by a Comparator
provided at map creation tim” 然而为了解决通过value来排序,我们需要找一个办法
- TreeMap有一个构造器接受Comparator,它能够通过key来对map排序
- 方法就是让comparator能够访问到values代替key
- 因此,我们通过map的方法 usingmap.get(key)得到values值,然后传入comparator
- 注意value必须实现Comparable类型,values对象必须实现Comparable接口,这里例子里面的String属于是Comparable类型
package com.collections.one;
import java.util.Map;
import java.util.TreeMap;
public class MapSort {
public static Map sortByValue(Map unsortedMap){
Map sortedMap = new TreeMap(new ValueComparator(unsortedMap));
sortedMap.putAll(unsortedMap);
return sortedMap;
}
public static Map sortByKey(Map unsortedMap){
Map sortedMap = new TreeMap();
sortedMap.putAll(unsortedMap);
return sortedMap;
}
}
package com.collections.one;
import java.util.Comparator;
import java.util.Map;
public class ValueComparator implements Comparator {
Map map;
public ValueComparator(Map map){
this.map = map;
}
public int compare(Object keyA, Object keyB){
Comparable valueA = (Comparable) map.get(keyA);
Comparable valueB = (Comparable) map.get(keyB);
System.out.println(valueA +" - "+valueB);
return valueA.compareTo(valueB);
}
}
package com.collections.one;
import java.util.HashMap;
import java.util.Map;
public class Test {
public static void main(String[] args){
Map map = new HashMap();
//*value Class should implements the Comparable interface
//*String implements Comparable by default.
map.put("Z", "3");
map.put("D", "4");
map.put("A", "1");
map.put("B", "2");
map.put("F", "6");
map.put("E", "5");
System.out.println("Unsorted Map: "+map);
System.out.println("Sorted Map By Values: "+MapSort.sortByValue(map));
System.out.println("Sorted Map By Keys: "+MapSort.sortByKey(map));
}
}
输出结果:
Unsorted Map: {D=4, E=5, F=6, A=1, B=2, Z=3}
5 - 4
6 - 4
6 - 5
1 - 5
1 - 4
2 - 5
2 - 4
2 - 1
3 - 5
3 - 2
3 - 4
Sorted Map By Values: {A=1, B=2, Z=3, D=4, E=5, F=6}
Sorted Map By Keys: {A=1, B=2, D=4, E=5, F=6, Z=3}
源码下载:
https://github.com/Harries/JAVA-TUTORIAL/tree/master/src/com/collections/one