根據map的value進行排序


JAVA對Map按Value值排序

在java實際編程中經常需要使用到HashMap,TreeMap以及LinkedHashMap來保存鍵值對,而java中對Map按Value排序並沒有已經寫好的方法,需要自己實現。
作者使用了自定義類以及Collections包的sort()方法實現Map的按值排序,具體代碼如下:

一、sortMap()  

  1、輸入參數為需要排序的Map,輸出為LinkedHashMap類型,因為需要保證順序。

public static LinkedHashMap<String, Integer> sortMap(Map<String, Integer> map){
        class MapClass{                                                            //自定義類保存鍵值對
            private String key;
            private int value;
            
            public MapClass(String key, int value) {
                super();
                this.key = key;
                this.value = value;
            }
 
            public String getKey() {
                return key;
            }
 
            public int getValue() {
                return value;
            }
            
            
        }
        class MapSortMethod implements Comparator<MapClass>{                    //為自定義類實現排序方法
            @Override
            public int compare(MapClass o1, MapClass o2) {
                int result = Integer.compare(o1.getValue(), o2.getValue());        //按值大小升序排列
                //int result = Integer.compare(o2.getValue(), o1.getValue());    //按值大小降序排列    
                if(result != 0)
                    return result;        
                return o1.getKey().compareTo(o2.getKey());                        //值相同時按鍵字典順序排列
            }
        }
        
        ArrayList<MapClass> mapclass = new ArrayList<MapClass>();                //以ArrayList保存自定義類
        for(String k: map.keySet())
            mapclass.add(new MapClass(k, map.get(k)));
        Collections.sort(mapclass, new MapSortMethod());                        //使用Collections.sort()方法,第二個參數為自定義排序方法,需要實現Comparator接口
                        
        LinkedHashMap<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
        for(MapClass m: mapclass)
            sortedMap.put(m.getKey(), m.getValue());
        return sortedMap;                                                        //用LinkedHashMap返回排好序的Map
    }

二、測試

    public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        map.put("math", 93);
        map.put("english", 88);
        map.put("chinese", 99);
        map.put("biology", 72);
        System.out.println(sortMap(map));
    }

三、結果

 

 注:本文用到的依賴有:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

 


免責聲明!

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



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