Java Map按值排序的正确姿势

2021-08-27 17:03:39 浏览数 (1)

在实际业务开发中,可能会遇到Java Map按值排序的需要。

Java Map按值排序的常见思路是

1、 将map中的entry放到List中

2、 对List中的entry通过比较器按值排序

3 、将排序后的entry放到linkedhashmap中

Java 8利用Stream

代码语言:javascript复制
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 {

        // 创建一个字符串为Key,数字为值的map
        Map 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 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);
    }


}

可以封装成工具类

代码语言:javascript复制
/**
 * Map排序工具类
 *
 * @author liuwangyanghdu@163.com  明明如月
 */
public class MapSortUtil {
    
    private static Comparator comparatorByKeyAsc = (Map.Entry o1, Map.Entry o2) -> {
        if (o1.getKey() instanceof Comparable) {
            return ((Comparable) o1.getKey()).compareTo(o2.getKey());
        }
        throw new UnsupportedOperationException("键的类型尚未实现Comparable接口");
    };


    private static Comparator comparatorByKeyDesc = (Map.Entry o1, Map.Entry o2) -> {
        if (o1.getKey() instanceof Comparable) {
            return ((Comparable) o2.getKey()).compareTo(o1.getKey());
        }
        throw new UnsupportedOperationException("键的类型尚未实现Comparable接口");
    };


    private static Comparator comparatorByValueAsc = (Map.Entry o1, Map.Entry o2) -> {
        if (o1.getValue() instanceof Comparable) {
            return ((Comparable) o1.getValue()).compareTo(o2.getValue());
        }
        throw new UnsupportedOperationException("值的类型尚未实现Comparable接口");
    };


    private static Comparator comparatorByValueDesc = (Map.Entry o1, Map.Entry o2) -> {
        if (o1.getValue() instanceof Comparable) {
            return ((Comparable) o2.getValue()).compareTo(o1.getValue());
        }
        throw new UnsupportedOperationException("值的类型尚未实现Comparable接口");
    };

    /**
     * 按键升序排列
     */
    public static  Map sortByKeyAsc(Map originMap) {
        if (originMap == null) {
            return null;
        }
        return sort(originMap, comparatorByKeyAsc);
    }

    /**
     * 按键降序排列
     */
    public static  Map sortByKeyDesc(Map originMap) {
        if (originMap == null) {
            return null;
        }
        return sort(originMap, comparatorByKeyDesc);
    }


    /**
     * 按值升序排列
     */
    public static  Map sortByValueAsc(Map originMap) {
        if (originMap == null) {
            return null;
        }
        return sort(originMap, comparatorByValueAsc);
    }

    /**
     * 按值降序排列
     */
    public static  Map sortByValueDesc(Map originMap) {
        if (originMap == null) {
            return null;
        }
        return sort(originMap, comparatorByValueDesc);
    }

    private static  Map sort(Map originMap, Comparator comparator) {
        return originMap.entrySet()
                .stream()
                .sorted(comparator)
                .collect(
                        Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2,
                                LinkedHashMap::new));
    }

}

测试类

代码语言:javascript复制
package com.chujianyun.common.map;

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;

import java.util.HashMap;
import java.util.Map;


/**
 * Map排序工具类
 *
 * @author liuwangyanghdu@163.com  明明如月
 */
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class MapSortUtilTest {
    // 创建一个字符串为Key,数字为值的map
    Map budget = new HashMap<>();

    @BeforeAll
    public void init() {
        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);
    }

    @Test
    void sortByKeyAsc() {
        System.out.println("按键升序"   MapSortUtil.sortByKeyAsc(budget));
    }

    @Test
    void sortByKeyDesc() {
        System.out.println("按键降序"   MapSortUtil.sortByKeyDesc(budget));
    }

    @Test
    void sortByValueAsc() {
        System.out.println("按值升序"   MapSortUtil.sortByValueAsc(budget));
    }

    @Test
    void sortByValueDesc() {
        System.out.println("按值降序"   MapSortUtil.sortByValueDesc(budget));
    }
}

Java 7版本

代码语言:javascript复制
import java.util.*; 
import java.lang.*; 

public class GFG { 

	//  hashmap按值排序
	public static HashMap sortByValue(HashMap hm) 
	{ 
		// HashMap的entry放到List中
		List > list = 
			new LinkedList >(hm.entrySet()); 

		//  对List按entry的value排序
		Collections.sort(list, new Comparator >() { 
			public int compare(Map.Entry o1, 
							Map.Entry o2) 
			{ 
				return (o1.getValue()).compareTo(o2.getValue()); 
			} 
		}); 
		
		// 将排序后的元素放到LinkedHashMap中
		HashMap temp = new LinkedHashMap(); 
		for (Map.Entry aa : list) { 
			temp.put(aa.getKey(), aa.getValue()); 
		} 
		return temp; 
	} 

	
	public static void main(String[] args) 
	{ 

		HashMap hm = new HashMap(); 

		// 填充测试数据
		hm.put("Math", 98); 
		hm.put("Data Structure", 85); 
		hm.put("Database", 91); 
		hm.put("Java", 95); 
		hm.put("Operating System", 79); 
		hm.put("Networking", 80); 
		Map hm1 = sortByValue(hm); 

		// 打印按值排序后的数据
		for (Map.Entry en : hm1.entrySet()) { 
			System.out.println("Key = "   en.getKey()   
						", Value = "   en.getValue()); 
		} 
	} 
} 

参考文章:

1、 Java 8 – Sorting HashMap by values in ascending and descending order

2、 Sort a Map by values

3、Sorting a Hashmap according to values

如果文章对你有帮助,欢迎点赞,关注,你的鼓励是我创作的最大动力!!

0 人点赞