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