/**
* map工具类
*
**/
public class MyMapUtils {
/**
* 根据map的key排序
* @methodName orderByKey
* @param map 原始map
* @param comparator 自定义比较
* @return java.util.Map<K,V>
*/
public static <K extends Comparable<? super K>, V extends Comparable<? super V>> Map<K, V> orderByKey(
Map<K, V> map, Comparator<K> comparator) {
if (CollectionUtil.isEmpty(map)) {
return map;
}
Map<K, V> result = Maps.newLinkedHashMapWithExpectedSize(map.size());
map.entrySet().stream().sorted(Map.Entry.comparingByKey(comparator))
.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
return result;
}
/**
* 根据map的key排序
* @methodName orderByKey
* @param map 原始map
* @param isDesc 是否降序
* @return java.util.Map<K,V>
*/
public static <K extends Comparable<? super K>, V extends Comparable<? super V>> Map<K, V> orderByKey(Map<K, V> map, boolean isDesc) {
if (CollectionUtil.isEmpty(map)) {
return map;
}
Map<K, V> result = Maps.newLinkedHashMapWithExpectedSize(map.size());
if (isDesc) {
map.entrySet().stream().sorted(Map.Entry.<K, V>comparingByKey().reversed())
.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
} else {
map.entrySet().stream().sorted(Map.Entry.comparingByKey())
.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
}
return result;
}
/**
* 根据map的value排序
* @methodName orderByValue
* @param map 原始map
* @param comparator 自定义比较
* @return java.util.Map<K,V>
*/
public static <K extends Comparable<? super K>, V extends Comparable<? super V>> Map<K, V> orderByValue(
Map<K, V> map,Comparator<V> comparator) {
if (CollectionUtil.isEmpty(map)) {
return map;
}
Map<K, V> result = Maps.newLinkedHashMapWithExpectedSize(map.size());
map.entrySet().stream().sorted(Map.Entry.comparingByValue(comparator))
.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
return result;
}
/**
* 根据map的value排序
* @methodName orderByValue
* @param map 原始map
* @param isDesc 是否降序
* @return java.util.Map<K,V>
*/
public static <K extends Comparable<? super K>, V extends Comparable<? super V>> Map<K, V> orderByValue(Map<K, V> map, boolean isDesc) {
if (CollectionUtil.isEmpty(map)) {
return map;
}
Map<K, V> result = Maps.newLinkedHashMapWithExpectedSize(map.size());
if (isDesc) {
map.entrySet().stream().sorted(Map.Entry.<K, V>comparingByValue().reversed())
.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
} else {
map.entrySet().stream().sorted(Map.Entry.comparingByValue())
.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
}
return result;
}
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(2, "a");
map.put(1, "b");
map.put(3, "c");
map.put(5, "d");
map.put(4, "e");
System.out.println("输入>>>>>>>>>"+map);
Map<Integer, String> kMap = orderByKey(map, true);
System.out.println("key倒序>>>>>>>>>"+kMap);
Map<Integer, String> vMap = orderByValue(map, false);
System.out.println("value正序>>>>>>>>>"+vMap);
}
}
Map排序工具类(正序,倒序)
于 2021-10-27 09:51:44 首次发布