一、Map順序簡介
Map是一種鍵值對形式存在的數據結構,其順序是由鍵的hashCode和equals方法確定的,它可以通過Iterator迭代器進行遍歷,也可以通過forEach方法實現Lambda表達式方式遍歷。
Map的順序與插入順序、put方法的先後順序、屬性值大小都沒有關係;而是由鍵的自然排序(natural ordering,如整數、字符串、日期等類型),或者在創建Map時所傳遞的Comparator所決定。
//使用自然排序 Map map = new TreeMap(); map.put("c", "ccccc"); map.put("a", "aaaaa"); map.put("b", "bbbbb"); for (Map.Entry entry : map.entrySet()) { System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue()); } //輸出 //Key : a Value : aaaaa //Key : b Value : bbbbb //Key : c Value : ccccc
二、Map順序的常見應用場景
1. 頻繁排序
如果我們需要頻繁對Map中的數據進行排序,那麼使用TreeMap是最優的選擇。當然,由於每次插入都需要進行排序,所以性能會受到一定影響,不過隨着JDK的不斷升級,TreeMap的性能也會不斷提高。
Map map = new TreeMap(); map.put(3,"ccc"); map.put(1,"aaa"); map.put(2,"bbb"); for(Map.Entry entry : map.entrySet()){ System.out.println("key : " + entry.getKey() + ", value : " + entry.getValue()); } //輸出 //key : 1, value : aaa //key : 2, value : bbb //key : 3, value : ccc
2. 多線程
如果需要在多線程環境中操作Map,那麼使用ConcurrentHashMap是最好的選擇。ConcurrentHashMap在多線程並發操作時採用了分段鎖的策略,不僅能夠保證線程安全性,而且在性能方面也有很大的提升。
ConcurrentMap map = new ConcurrentHashMap(); map.put("key1", "value1"); map.put("key2", "value2"); map.put("key3", "value3"); for (Map.Entry entry : map.entrySet()) { System.out.println(entry.getKey() + " : " + entry.getValue()); } //輸出 //key2 : value2 //key1 : value1 //key3 : value3
三、反思Map順序
1. Map順序為什麼要這樣設計?
因為Map的用途是用來快速查找的,如果按照插入順序排列,那麼每一次操作的時間複雜度就會增加;而按照鍵的HashCode和equals方法進行排序,則能夠保證在O(1)時間內完成元素的查找。
2. 如何自定義Map的順序?
如果我們需要按照自己的方式對Map進行排序,可以在創建TreeMap時傳遞一個Comparator給它。
Map scoreMap = new TreeMap(new Comparator() { @Override public int compare(Student o1, Student o2) { return Integer.compare(o2.getScore(), o1.getScore()); } }); scoreMap.put(new Student("Tom", 80), "B"); scoreMap.put(new Student("Marry", 90), "A"); scoreMap.put(new Student("Lucy", 70), "C"); for (Map.Entry entry : scoreMap.entrySet()) { System.out.println("Student : " + entry.getKey().getName() + ", Score : " + entry.getKey().getScore() + ", Grade : " + entry.getValue()); } //輸出 //Student : Marry, Score : 90, Grade : A //Student : Tom, Score : 80, Grade : B //Student : Lucy, Score : 70, Grade : C
四、總結
在日常開發中,Map是我們常用的一種數據結構,它能夠幫助我們快速完成功能的實現。在使用Map時,我們應該了解它的順序特性,並根據實際需求來選擇最適合的Map實現。
原創文章,作者:XXIK,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/136416.html