public class MapUtil {
public static Map<String, String> sortByKey(Map<String, String> map) {
if (map == null || map.isEmpty()) {
return null;
}
Map<String, String> sortMap = new TreeMap<>((str1, str2) -> str1.compareTo(str2));
sortMap.putAll(map);
return sortMap;
}
public static Map<String, String> sortByKeyIgnoreCase(Map<String, String> map) {
if (map == null || map.isEmpty()) {
return null;
}
Map<String, String> sortMap = new TreeMap<>((str1, str2) -> str1.toLowerCase().compareTo(str2.toLowerCase()));
sortMap.putAll(map);
return sortMap;
}
public static Map<String, String> sortByValue(Map<String, String> oriMap) {
if (oriMap == null || oriMap.isEmpty()) {
return null;
}
Map<String, String> sortedMap = new LinkedHashMap<>();
List<Map.Entry<String, String>> entryList = new ArrayList<>(oriMap.entrySet());
Collections.sort(entryList, (me1, me2) -> me1.getValue().compareTo(me2.getValue()));
Iterator<Map.Entry<String, String>> iterator = entryList.iterator();
Map.Entry<String, String> tmpEntry;
while (iterator.hasNext()) {
tmpEntry = iterator.next();
sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
}
return sortedMap;
}
public static Map<String, String> sortByValueIgnoreCase(Map<String, String> oriMap) {
if (oriMap == null || oriMap.isEmpty()) {
return null;
}
Map<String, String> sortedMap = new LinkedHashMap<>();
List<Map.Entry<String, String>> entryList = new ArrayList<>(oriMap.entrySet());
Collections.sort(entryList, (me1, me2) -> me1.getValue().toLowerCase().compareTo(me2.getValue().toLowerCase()));
Iterator<Map.Entry<String, String>> iterator = entryList.iterator();
Map.Entry<String, String> tmpEntry;
while (iterator.hasNext()) {
tmpEntry = iterator.next();
sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
}
return sortedMap;
}
}
版权声明:本文为ecjtuhq原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。