一、通过自己实现Comparator接口排序
根据key进行排序
/**
* 对Map按key进行排序
* @param map 等待排序的map
* @param isAsc true: 升序,false: 降序
* @return 排序后的map
*/
public static Map<String, String> sortMapByStrKey(Map<String, String> map, boolean isAsc) {
if (MapUtils.isEmpty(map)) {
// 这样调用方法的地方就不用担心空指针了
return Maps.newHashMap();
}
// TreeMap默认按key升序排序
Map<String, String> sortMap = new TreeMap<>(new MapKeyComparator(isAsc));
sortMap.putAll(map);
return sortMap;
}
private static class MapKeyComparator implements Comparator<String> {
private boolean isAsc;
MapKeyComparator(boolean isAsc) {
this.isAsc = isAsc;
}
@Override
public int compare(String o1, String o2) {
return isAsc ? o1.compareTo(o2) : o2.compareTo(o1);
}
}
二、通过stream.sorted()和list.sort()方法来排序
根据value进行排序
/**
* 对Map按value排序(升序)
*/
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValueAsc(Map<K, V> map) {
if (MapUtils.isEmpty(map)) {
// 这样调用方法的地方就不用担心空指针了
return Maps.newHashMap();
}
// LinkedHashMap可以通过构造方法指定是按放入的顺序,还是get顺序 排序
Map<K, V> result = Maps.newLinkedHashMap();
Stream<Map.Entry<K, V>> st = map.entrySet().stream();
st.sorted(Comparator.comparing(Map.Entry::getValue)).forEach(e -> result.put(e.getKey(), e.getValue()));
return result;
}
/**
* 对Map按value排序(降序)
*/
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValueDesc(Map<K, V> map) {
List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
// 同理 o1, o2换一下就是升序排序了
list.sort((o1, o2) -> (o2.getValue()).compareTo(o1.getValue()));
Map<K, V> result = new LinkedHashMap<>();
list.forEach(kvEntry -> result.put(kvEntry.getKey(), kvEntry.getValue()));
return result;
}
三、通过jdk8流式操作进行排序
根据key或value进行排序
/**
* 根据key对map进行排序
*
* @param map 等待排序的map
* @param asc true: 升序,false: 降序
* @param <K> key的类型
* @param <V> value的类型
* @return 排序后的map
*/
public static <K extends Comparable<? super K>, V> Map<K, V> sortMapByKey(Map<K, V> map, boolean asc) {
Map<K, V> result = Maps.newLinkedHashMap();
if (asc) {
map.entrySet().stream().sorted(Map.Entry.comparingByKey())
.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
} else {
map.entrySet().stream().sorted(Map.Entry.<K, V>comparingByKey().reversed())
.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
}
return result;
}
/**
* 根据value对map进行排序
*
* @param map 等待排序的map
* @param asc true: 升序,false: 降序
* @param <K> key的类型
* @param <V> value的类型
* @return 排序后的map
*/
public static <K, V extends Comparable<? super V>> Map<K, V> sortMapByValue(Map<K, V> map, boolean asc) {
Map<K, V> result = Maps.newLinkedHashMap();
if (asc) {
map.entrySet().stream().sorted(Map.Entry.comparingByValue())
.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
} else {
map.entrySet().stream().sorted(Map.Entry.<K, V>comparingByValue().reversed())
.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
}
return result;
}
小结
使用时可根据需要作出修改