Java Map按照key或value排序

import java.util.*;

public class MapKeySort {
    public static void main(String[] args) {
        Map<String, String> map = new LinkedHashMap<>();
        map.put("Wang", "B");
        map.put("Zhang", "A");
        map.put("Li", "C");
        map.put("1", "B");
        map.put("3", "A");
        map.put("2", "C");
        map = MapKeySort.sortMapByKey(map);
//        System.out.println(map);
        for (Map.Entry<String, String> mapEntry : map.entrySet()) {
            System.out.println(mapEntry);
        }
    }

    // 新的map(新的map需为LinkedHashMap,可按照put的顺序get)按排序后的key进行put
    public static Map<String, String> sortMapByKey(Map<String, String> map) {
        Set<String> mapKeySet = map.keySet();
        // 等效写法一
//        Set<String> newMapKeySet = new TreeSet<>(new Comparator<String>(){
//            @Override
//            public int compare(String o1, String o2) {
//                return o1.compareTo(o2);
//            }
//        });
        // 等效写法二
//        Set<String> newMapKeySet = new TreeSet<>((o1, o2) -> o1.compareTo(o2));
        // 等效写法三
//        Set<String> newMapKeySet = new TreeSet<>(String::compareTo);
        // 等效写法四,Comparator.naturalOrder()为升序
//        Set<String> newMapKeySet = new TreeSet<>(Comparator.naturalOrder());
//        newMapKeySet.addAll(mapKeySet);
        // 等效写法五,默认为字符升序排序,非默认则采用其他写法
        Set<String> newMapKeySet = new TreeSet<>(mapKeySet);
        // 只适用于数字
//        newMapKeySet.stream().sorted(Comparator.naturalOrder());
        Map<String, String> newMap = new LinkedHashMap<>();
        for (String key : newMapKeySet) {
            newMap.put(key, map.get(key));
        }

        return newMap;
    }

    // key降序
    public static <K extends Comparable<? super K>, V> Map<K, V> sortMapByKeyWithDescend(Map<K, V> map) {
        List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
        Collections.sort(list, (o1, o2) -> {
            int compare = (o1.getKey()).compareTo(o2.getKey());
            return -compare;
        });

        Map<K, V> result = new LinkedHashMap<>();
        for (Map.Entry<K, V> entry : list) {
            result.put(entry.getKey(), entry.getValue());
        }

        return result;
    }

    // key升序
    public static <K extends Comparable<? super K>, V> Map<K, V> sortMapByKeyWithAscend(Map<K, V> map) {
        List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
        Collections.sort(list, (o1, o2) -> {
            int compare = (o1.getKey()).compareTo(o2.getKey());
            return compare;
        });

        Map<K, V> result = new LinkedHashMap<>();
        for (Map.Entry<K, V> entry : list) {
            result.put(entry.getKey(), entry.getValue());
        }

        return result;
    }

    // value降序
    public static <K, V extends Comparable<? super V>> Map<K, V> sortMapByValueWithDescend(Map<K, V> map) {
        List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
        Collections.sort(list, (o1, o2) -> {
            int compare = (o1.getValue()).compareTo(o2.getValue());
            return -compare;
        });

        Map<K, V> result = new LinkedHashMap<>();
        for (Map.Entry<K, V> entry : list) {
            result.put(entry.getKey(), entry.getValue());
        }
        
        return result;
    }

    // value升序
    public static <K, V extends Comparable<? super V>> Map<K, V> sortMapByValueWithAscend(Map<K, V> map) {
        List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
        Collections.sort(list, (o1, o2) -> {
            int compare = (o1.getValue()).compareTo(o2.getValue());
            return compare;
        });

        Map<K, V> result = new LinkedHashMap<>();
        for (Map.Entry<K, V> entry : list) {
            result.put(entry.getKey(), entry.getValue());
        }
        
        return result;
    }

    // 将Map的entrySet按key排序,只适用于数字
    // 实验失败,newMapEntrySet.stream().sorted(Comparator.comparing(Map.Entry::getKey));效果达不到预期,建议官方完善
    /*public static Map<String, String> sortMapByKey(Map<String, String> map){
        // 克隆,覆盖原有
//        map = new LinkedHashMap<>(map);
        // 克隆,不改变原有
        Map<String, String> newMap = new LinkedHashMap<>(map);
        Set<Map.Entry<String, String>> newMapEntrySet = newMap.entrySet();
        // 等效方法一,只适用于数字
//        newMapEntrySet.stream().sorted((o1, o2) -> o1.getKey().compareTo(o2.getKey()));
        // 等效方法二,只适用于数字
        newMapEntrySet.stream().sorted(Comparator.comparing(Map.Entry::getKey));
        // 不可行,因为Map.Entry未继承Comparable接口
//        Set<Map.Entry<String, String>> newMapEntrySet1 = new TreeSet<>(newMapEntrySet);
        // 不可行,因为Map.Entry未继承Comparable接口
//        newMapEntrySet1.addAll(newMapEntrySet);
        return newMap;
    }*/
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Java Map 是一个不保证顺序的集合类。如果需要按照 KeyValue 排序,可以通过以下方式实现: 按 Key 排序: 可以将 Map 中的 Entry 对象放到一个 List 中,然后对 List 中的 Entry 对象进行排序,最后将排序后的 Entry 对象重新放回 Map 中。 示例代码如下: ``` Map<String, Integer> map = new HashMap<>(); map.put("a", 3); map.put("c", 1); map.put("b", 2); List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet()); Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() { @Override public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { return o1.getKey().compareTo(o2.getKey()); } }); Map<String, Integer> sortedMap = new LinkedHashMap<>(); for (Map.Entry<String, Integer> entry : list) { sortedMap.put(entry.getKey(), entry.getValue()); } System.out.println(sortedMap); // 输出 {a=3, b=2, c=1} ``` 按 Value 排序: 与按 Key 排序类似,也是先将 Map 中的 Entry 对象放到一个 List 中,但是排序时比较的是 Entry 对象的 Value。 示例代码如下: ``` Map<String, Integer> map = new HashMap<>(); map.put("a", 3); map.put("c", 1); map.put("b", 2); List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet()); Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() { @Override public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { return o1.getValue().compareTo(o2.getValue()); } }); Map<String, Integer> sortedMap = new LinkedHashMap<>(); for (Map.Entry<String, Integer> entry : list) { sortedMap.put(entry.getKey(), entry.getValue()); } System.out.println(sortedMap); // 输出 {c=1, b=2, a=3} ``` 需要注意的是,排序后的 Map 仍然是一个不保证顺序的集合类,只是按照 KeyValue 排序了。如果需要保证顺序,可以使用 LinkedHashMap

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风铃峰顶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值