HashMap和TreeMap的常用排序方法


一、簡單描述

Map是鍵值對的集合接口,它的實現類主要包括:HashMap,TreeMap,HashTable以及LinkedHashMap等。

TreeMap:能夠把它保存的記錄根據鍵(key)排序,默認是按升序排序,也可以指定排序的比較器,該映射根據其鍵的自然順序進行排序,或者根據創建映射時提供的 Comparator 進行排序,具體取決於使用的構造方法。

HashMap的值是沒有順序的,它是按照key的HashCode來實現的,根據鍵可以直接獲取它的值,具有很快的訪問速度。HashMap最多只允許一條記錄的鍵為Null(多條會覆蓋);允許多條記錄的值為 Null。非同步的。

 

TreeMap默認是升序的,如果我們需要改變排序方式,則需要使用比較器:Comparator。

        
        Map< Integer, String> map=new TreeMap<>(new Comparator<Integer>() {
            
            @Override
            public int compare(Integer o1, Integer o2) {
//                return o1.compareTo(o2);       //按照key值大小升序排列       -o1.compareTo(o2)即o2.compareTo(o1)按照key值大小降序排列
                return -1;                     //按put反順序排序      1則為 put順序排列
            }
        });
        map.put(5, "a");
        map.put(3, "c");
        map.put(4, "b");
        map.put(2, "d");
        map.put(1, "e");
        for(Entry<Integer, String> aEntry:map.entrySet()) {
            System.out.println(aEntry.getKey()+":"+aEntry.getValue());
        }
    

如果想通過key值排序  則需要通過List解決

Map< Integer, String> map=new TreeMap<>();
        map.put(5, "a");
        map.put(3, "c");
        map.put(4, "b");
        map.put(2, "d");
        map.put(1, "e");
        List<Entry<Integer,String>> list =new ArrayList<Entry<Integer,String>>(map.entrySet());
        Collections.sort(list, new Comparator<Entry<Integer, String>>() {

            @Override
            public int compare(Entry<Integer, String> o1, Entry<Integer, String> o2) {
                // TODO Auto-generated method stub
                return o1.getValue().compareTo(o2.getValue());
            }
        });
        for(Entry<Integer, String> aEntry:list) {
            System.out.println(aEntry.getKey()+":"+aEntry.getValue());
        }

運行結果為:

5:a
4:b
3:c
2:d
1:e

對於HashMap來說  沒法使用比較器:Comparator  則可以用TreeMap的第二種方法  代碼一樣

最后友情提示一點:

有時候代碼沒問題 list老是報錯(The type List is not generic; it cannot be parameterized with arguments )

則是自動導入了import java.awt.List;而不是import java.util.List;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM