zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Map的有序性_有序的map集合有哪些

Map集合 哪些 有序 有序性
2023-06-13 09:14:49 时间

大家好,又见面了,我是你们的朋友全栈君。

//使用LinkedHashMap代替无序的HashMap实现

 public static void main(String[] args) {

        /**
     * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
     * with the default initial capacity (16) and load factor (0.75).
     */
        Map<String,Integer> linkedMap = new LinkedHashMap();
        linkedMap.put("a",14);
        linkedMap.put("c",18);
        linkedMap.put("x",19);

/**
    默认排序,支持comparable排序方式自定义
*/
        Map<String,Integer> treeMap = new TreeMap();
        treeMap.put("a",11);
        treeMap.put("x",10);
        treeMap.put("c",9);
        treeMap.put("b",100);

    /**
     * Constructs an empty <tt>HashMap</tt> with the default initial capacity
     * (16) and the default load factor (0.75).
     */
        Map<String,Integer> hashMap = new HashMap<>();
        hashMap.put("a",11);
        hashMap.put("x",10);
        hashMap.put("e",9);
        hashMap.put("b",100);
        for (Map.Entry<String, Integer> entry : linkedMap.entrySet()){
            System.out.println(entry.getKey()+"===="+entry.getValue());
        }
        System.out.println("========我是分割线=======");
        for (Map.Entry<String, Integer> entry : treeMap.entrySet()){
            System.out.println(entry.getKey()+"===="+entry.getValue());
        }
        System.out.println("========我是分割线=======");
        for (Map.Entry<String, Integer> entry : hashMap.entrySet()){
            System.out.println(entry.getKey()+"===="+entry.getValue());
        }
        //System.out.println(result);
    }

HashMap ;无序,高效

TreeMap:能够根据主键自动进行排序

LinkedHashMap:先进先出…即按照add的先后顺序排序.

LinkedHashMap是一个链表的数组.基于HashMap的链表方式实现机制.具有高效性,同时在内部增加了一个链表,用以存放元素的顺序.根据元素增加或者访问的先后顺序进行排序.

HashMap的一个功能缺点是他的无序性,被存入到HashMap中的元素,在遍历HashMap时,其输出是无序的.

TreeMap提供了一种完全不同的Map实现.TreeMap有着比HashMap更为强大的功能,实现了SortedMap接口.TreeMap的迭代输出将会以元素顺序进行.TreeMap的排序则根据元素的key进行排序,是基于元素的固有顺序(由Comparator或者Comparable确定)

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/190359.html原文链接:https://javaforall.cn