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; } }
Map排序工具类
最新推荐文章于 2021-03-12 12:26:22 发布