import java.util.*;
public class MapSortDemo {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("1", "4");
map.put("3", "3");
map.put("2", "2");
map.put("4", "1");
//Map<String, String> resultMap = sortMapByKey(map); //按Key进行排序:1.treemap的性质
Map<String, String> resultMap = sortMapByKey2(map); //按key进行排序:2.list,自定义比较器(排序后需要LinkedHashMap保存)
// Map<String, String> resultMap = sortMapByValue(map); //按Value进行排序:list,自定义比较器
for (Map.Entry<String, String> entry : resultMap.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
/**
* 使用 TreeMap的性质按key进行排序
* @param map
* @return
*/
public static Map<String, String> sortMapByKey(Map<String, String> map) {
if (map == null || map.isEmpty()) {
return null;
}
//TreeMap默认用key的自然排序,所以不用声明比较器也可以实现key排序,比较器可以自定义排序规则,比如倒序
//Map<String, String> sortMap = new TreeMap<String, String>();
//TreeMap构造方法可以有比较器参数~但是比较器只能是对key进行比较
Map<String, String> sortMap = new TreeMap<String, String>(new MapKeyComparator());
sortMap.putAll(map);
return sortMap;
}
/**
* 使用 list按key进行排序
* @param map
* @return
*/
public static Map<String, String> sortMapByKey2(Map<String, String> map) {
if (map == null || map.isEmpty()) {
return null;
}
List<Map.Entry<String,String>> list = new ArrayList<>(map.entrySet());
Collections.sort(list,new MapKeyComparator2());
Map<String, String> sortMap = new LinkedHashMap<>();
Iterator<Map.Entry<String, String>> iterable = list.iterator();
while (iterable.hasNext()){
Map.Entry<String, String> tmpEntry = iterable.next();
sortMap.put(tmpEntry.getKey(),tmpEntry.getValue());
}
return sortMap;
}
/**
* 使用 List对Map按value进行排序
* @param oriMap
* @return
*/
public static Map<String, String> sortMapByValue(Map<String, String> oriMap) {
if (oriMap == null || oriMap.isEmpty()) {
return null;
}
//一定是LinkedHashMap,因为LinkedHashMap保证put顺序和输出顺序一致!
Map<String, String> sortedMap = new LinkedHashMap<>();
//map.entry把map的<key,value>当节点装进list,对list排序
List<Map.Entry<String, String>> entryList = new ArrayList<>(oriMap.entrySet());
Collections.sort(entryList, new MapValueComparator());
Iterator<Map.Entry<String, String>> iter = entryList.iterator();
Map.Entry<String, String> tmpEntry = null;
while (iter.hasNext()) {
tmpEntry = iter.next();
sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
}
return sortedMap;
}
}
class MapKeyComparator implements Comparator<String> {
@Override
public int compare(String str1, String str2) {
return str2.compareTo(str1);
}
}
class MapValueComparator implements Comparator<Map.Entry<String, String>> {
@Override
public int compare(Map.Entry<String, String> me1, Map.Entry<String, String> me2) {
return me1.getValue().compareTo(me2.getValue());
}
}
class MapKeyComparator2 implements Comparator<Map.Entry<String, String>> {
@Override
public int compare(Map.Entry<String, String> me1, Map.Entry<String, String> me2) {
return me1.getKey().compareTo(me2.getKey());
}
}
原文地址:http://blog.51cto.com/13580976/2147994