使用比较器对Treemap按照key进行排序

本文详细介绍了如何使用比较器对Treemap进行key排序,包括两种实现方式:自定义比较器类和直接在创建Treemap时指定比较器。通过对key的比较规则设置,确保了Treemap中的元素按特定顺序排列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用比较器对Treemap按照key进行排序

一.理论准备

    Map是键值对的集合接口,它的实现类主要包括:HashMap,TreeMap,Hashtable以及LinkedHashMap等。

    TreeMap:基于红黑树(Red-Black tree)的 NavigableMap 实现,该映射根据其键的自然顺序进行排序,或者根据创建映射时提供的 Comparator 进行排序,具体取决于使用的构造方法。

    HashMap的值是没有顺序的,它是按照key的HashCode来实现的,对于这个无序的HashMap我们要怎么来实现排序呢?参照TreeMap的value排序。

    Map.Entry返回Collections视图

    key排序
    TreeMap默认是升序的,如果我们需要改变排序方式,则需要使用比较器:Comparator。Comparator可以对集合对象或者数组进行排序的比较器接口,实现该接口的public compare(T o1,To2)方法即可实现排序,如下:

方式一

public class MapSortDemo {

    public static void main(String[] args) {

        Map<String, String> map = new TreeMap<String, String>();

        map.put("KFC", "kfc");
        map.put("WNBA", "wnba");
        map.put("NBA", "nba");
        map.put("CBA", "cba");

        Map<String, String> resultMap = sortMapByKey(map);  //按Key进行排序

        for (Map.Entry<String, String> entry : resultMap.entrySet()) {
            System.out.println(entry.getKey() + " " + entry.getValue());
        }
    }

    /**
     * 使用 Map按key进行排序
     * @param map
     * @return
     */
    public static Map<String, String> sortMapByKey(Map<String, String> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }

        Map<String, String> sortMap = new TreeMap<String, String>(
                new MapKeyComparator());

        sortMap.putAll(map);

        return sortMap;
    }
}

比较器类

class MapKeyComparator implements Comparator<String>{

    @Override
    public int compare(String str1, String str2) {

        return str1.compareTo(str2);
    }
}

方式二:

public class TreeMapTest {

    public static void main(String[] args) {

        Map<String, String> map = new TreeMap<String, String>(

                new Comparator<String>() {

                    public int compare(String obj1, String obj2) {

                        // 降序排序

                        return obj2.compareTo(obj1);

                    }

                });

        map.put("b", "ccccc");

        map.put("d", "aaaaa");

        map.put("c", "bbbbb");

        map.put("a", "ddddd");



        Set<String> keySet = map.keySet();

        Iterator<String> iter = keySet.iterator();

        while (iter.hasNext()) {

            String key = iter.next();

            System.out.println(key + ":" + map.get(key));

        }

    }

}

        运行结果如下:

d:aaaaa

c:bbbbb

b:ccccc

a:ddddd
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值