Map排序工具类

public class MapUtil {

    public static Map sortByKey(Map map) {
        if (map == null || map.isEmpty()) {
            return null;
        }

        Map sortMap = new TreeMap<>((str1, str2) -> str1.compareTo(str2));
        sortMap.putAll(map);
        return sortMap;
    }

    public static Map sortByKeyIgnoreCase(Map map) {
        if (map == null || map.isEmpty()) {
            return null;
        }

        Map sortMap = new TreeMap<>((str1, str2) -> str1.toLowerCase().compareTo(str2.toLowerCase()));
        sortMap.putAll(map);
        return sortMap;
    }

    public static Map sortByValue(Map oriMap) {
        if (oriMap == null || oriMap.isEmpty()) {
            return null;
        }

        Map sortedMap = new LinkedHashMap<>();
        List> entryList = new ArrayList<>(oriMap.entrySet());
        Collections.sort(entryList, (me1, me2) -> me1.getValue().compareTo(me2.getValue()));

        Iterator> iterator = entryList.iterator();
        Map.Entry tmpEntry;
        while (iterator.hasNext()) {
            tmpEntry = iterator.next();
            sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
        }
        return sortedMap;
    }

    public static Map sortByValueIgnoreCase(Map oriMap) {
        if (oriMap == null || oriMap.isEmpty()) {
            return null;
        }

        Map sortedMap = new LinkedHashMap<>();
        List> entryList = new ArrayList<>(oriMap.entrySet());
        Collections.sort(entryList, (me1, me2) -> me1.getValue().toLowerCase().compareTo(me2.getValue().toLowerCase()));

        Iterator> iterator = entryList.iterator();
        Map.Entry tmpEntry;
        while (iterator.hasNext()) {
            tmpEntry = iterator.next();
            sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
        }
        return sortedMap;
    }
}

你可能感兴趣的:(Android,Java)