溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Map怎么實現(xiàn)按單個或多個Value排序

發(fā)布時間:2023-02-07 09:36:52 來源:億速云 閱讀:125 作者:iii 欄目:開發(fā)技術

本篇內(nèi)容主要講解“Map怎么實現(xiàn)按單個或多個Value排序”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“Map怎么實現(xiàn)按單個或多個Value排序”吧!

Map可以先按照value進行排序,然后按照key進行排序。 或者先按照key進行排序,然后按照value進行排序,這都是可以的。

并且,大家可以制定自己的排序規(guī)則。
按單個value排序:

import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
 
import static java.util.Map.Entry.comparingByValue;
import static java.util.stream.Collectors.toMap;
 
public class SortTest {
 
    public static void main(String[] args) throws Exception {
 
        // 創(chuàng)建一個字符串為Key,數(shù)字為值的map
        Map<String, Integer> budget = new HashMap<>();
        budget.put("clothes", 120);
        budget.put("grocery", 150);
        budget.put("transportation", 100);
        budget.put("utility", 130);
        budget.put("rent", 1150);
        budget.put("miscellneous", 90);
        System.out.println("排序前: " + budget);
 
        // 按值排序 升序
        Map<String, Integer> sorted = budget
                .entrySet()
                .stream()
                .sorted(comparingByValue())
                .collect(
                        toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2,
                                LinkedHashMap::new));
 
        System.out.println("升序按值排序后的map: " + sorted);
 
        // 按值排序降序
        sorted = budget
                .entrySet()
                .stream()
                .sorted(Collections.reverseOrder(comparingByValue()))
                .collect(
                        toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2,
                                LinkedHashMap::new));
 
        System.out.println("降序按值排序后的map: " + sorted);
    }
}

按多個value排序:

data = data.stream().sorted(Comparator.comparing(o -> {
    StringBuffer key = new StringBuffer();
    fieldList.stream().forEach((a)-> {
        key.append(o.get(a)+"");
    });
    return key.toString();
} )).collect(Collectors.toList());

下面的代碼中,首先按照value的數(shù)值從大到小進行排序,當value數(shù)值大小相同時,再按照key的長度從長到短進行排序,這個操作與Stream流式操作相結合。

    /**
     * Map按照整數(shù)型的value進行降序排序,當value相同時,按照key的長度進行排序
     *
     * @param map
     * @return
     */
    public static LinkedHashMap<String, Integer> sortMap(Map<String, Integer> map) {
        return map.entrySet().stream().sorted(((item1, item2) -> {
            int compare = item2.getValue().compareTo(item1.getValue());
            if (compare == 0) {
                if (item1.getKey().length() < item2.getKey().length()) {
                    compare = 1;
                } else if (item1.getKey().length() > item2.getKey().length()) {
                    compare = -1;
                }
            }
            return compare;
        })).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
    }

補充:對Map中的Value進行降序排序,當Value相同時,按照Key降序排序

package com.ethjava;
import java.util.*;
public class mappaixu1 {
    public static void main(String[] args){
 
        Map<Integer,Integer> hashMap=new HashMap<Integer, Integer>();
        hashMap.put(1,10);
        hashMap.put(5,7);
        hashMap.put(2,9);
        hashMap.put(3,7);
        hashMap.put(3,6);//key是不可重復的,當這里再次輸入Key=3時的,將會覆蓋掉前面的(3,7)
        hashMap.put(4,7);
 
        //遍歷
        for(Map.Entry<Integer,Integer> e:hashMap.entrySet()){
            System.out.println("Key: "+e.getKey()+"對應的Value: "+e.getValue());
        }
        //Key: 1對應的Value: 10
        //Key: 2對應的Value: 9
        //Key: 3對應的Value: 6
        //Key: 4對應的Value: 7
        //Key: 5對應的Value: 7
        //這里為什么自動按照key升序排序輸出???為什么
        // 某夢說,這里是因為湊巧正序輸出,hashMap輸出相對于輸入是無序的。
 
        //下面按照Value進行倒序排列
        ArrayList<Map.Entry<Integer,Integer>> arrayList=new ArrayList<Map.Entry<Integer, Integer>>(hashMap.entrySet());
 
        Collections.sort(arrayList,new Comparator<Map.Entry<Integer,Integer>>(){
            @Override
 
            public int compare(Map.Entry<Integer,Integer> o1,Map.Entry<Integer,Integer> o2 ){
                //按照Value進行倒序,若Value相同,按照Key正序排序
                //方法1:return o2.getValue() - o1.getValue();
                //方法2:return o2.getValue().compareTo(o1.getValue());//對于Integer,String都是可以應用的
                //按照Value進行倒序,若Value相同,按照Key倒序排序
                int result = o2.getValue().compareTo(o1.getValue());
                //方法學習:public int compareTo( NumberSubClass referenceName )
                //referenceName -- 可以是一個 Byte, Double, Integer, Float, Long 或 Short 類型的參數(shù)。
                //返回值:如果指定的數(shù)與參數(shù)相等返回0。
                // 如果指定的數(shù)小于參數(shù)返回 -1。
                //如果指定的數(shù)大于參數(shù)返回 1
                if(result!=0){
                    return result;//即兩個Value不相同,就按照Value倒序輸出
                }else{
                    return o2.getKey().compareTo(o1.getKey());}
                    //若兩個Value相同,就按照Key倒序輸出
            }
        });
        //這里arrayList里的順序已經(jīng)按照自己的排序進行了調(diào)整
        for(int i=0;i<arrayList.size();i++){
            System.out.println(arrayList.get(i));
            //方法一和方法二輸出:
            //1=10
            //2=9
            //4=7
            //5=7
            //3=6
            //當按照Value倒序排序,但是當Value相同時,按照Key順序正序排序
 
            //方法二
            //1=10
            //2=9
            //5=7
            //4=7
            //3=6
            //當按照Value倒序輸出,但是當Value相同時,按照Key倒序輸出
        }
 
        for(Map.Entry<Integer,Integer> e:hashMap.entrySet()){
 
            System.out.println(e);
            //1=10
            //2=9
            //3=6
            //4=7
            //5=7
            //這里表明hashMap中存取的內(nèi)容順序并沒有進行任何改變,改變的是arrayList里的內(nèi)容的順序
        }
    }
}

到此,相信大家對“Map怎么實現(xiàn)按單個或多個Value排序”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關內(nèi)容可以進入相關頻道進行查詢,關注我們,繼續(xù)學習!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI