TreeMap升序|降序排列和按照value進行排序


TreeMap 升序|降序排列

import java.util.Comparator;
import java.util.TreeMap;
public class Main {
    public static void main(String[] args) {
        TreeMap<Integer,Integer> map1 = new TreeMap<Integer,Integer>();  //默認的TreeMap升序排列
        TreeMap<Integer,Integer> map2= new TreeMap<Integer,Integer>(new Comparator<Integer>(){
             /* 
             * int compare(Object o1, Object o2) 返回一個基本類型的整型, 
             * 返回負數表示:o1 小於o2, 
             * 返回0 表示:o1和o2相等, 
             * 返回正數表示:o1大於o2。 
             */  
            public int compare(Integer a,Integer b){
                return b-a;            
            }
            });
        map2.put(1,2);
        map2.put(2,4);
        map2.put(7, 1);
        map2.put(5,2);
        System.out.println("Map2="+map2);  
        
        map1.put(1,2);
        map1.put(2,4);
        map1.put(7, 1);
        map1.put(5,2);
        System.out.println("map1="+map1);
    }
}

TreeMap按照value進行排序

TreeMap底層是根據紅黑樹的數據結構構建的,默認是根據key的自然排序來組織(比如integer的大小,String的字典排序)。所以,TreeMap只能根據key來排序,是不能根據value來排序的(否則key來排序根本就不能形成TreeMap)。

今天有個需求,就是要根據treeMap中的value排序。所以網上看了一下,大致的思路是把TreeMap的EntrySet轉換成list,然后使用Collections.sor排序。代碼:

public static void sortByValue() {
        Map<String,String> map = new TreeMap<String,String>();
        map.put("a", "dddd");
        map.put("d", "aaaa");
        map.put("b", "cccc");
        map.put("c", "bbbb");
        
        List<Entry<String, String>> list = new ArrayList<Entry<String, String>>(map.entrySet());
        
        Collections.sort(list,new Comparator<Map.Entry<String,String>>() {
            //升序排序
            public int compare(Entry<String, String> o1, Entry<String, String> o2) {
                return o1.getValue().compareTo(o2.getValue());
            }
        });
        
        for (Entry<String, String> e: list) {
            System.out.println(e.getKey()+":"+e.getValue());
        }
    }

 


免責聲明!

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



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