Java基础 —— 根据 Key 或是 Value 对 Map 进行排序

how to sort Map values by key in Java

https://stackoverflow.com/questions/922528/how-to-sort-map-values-by-key-in-java

Sort a Map<Key, Value> by values (Java)

https://stackoverflow.com/questions/109383/sort-a-mapkey-value-by-values-java


根据 Key 对 Map 进行排序

package com.practice.map;

import java.util.*;

public class SortedMapByKey {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("abc", 122);
        map.put("bsh", 232);
        map.put("dsa", 12);
        map.put("aac", 192);

        System.out.println("未对 Key 进行排序:");
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println("\"" + entry.getKey() + "\"" + " : " + entry.getValue());
        }

        System.out.println("-----------------------------");

        System.out.println("使用 Collections.sort 对 Key 进行排序:");
        List<String> sortedKeys = new ArrayList(map.keySet());
        Collections.sort(sortedKeys);
        for (String key : sortedKeys){
            System.out.println("\"" + key + "\"" + " : " + map.get(key));
        }

        System.out.println("-----------------------------");

        System.out.println("使用 TreeMap 对 Key 进行排序:");
        Map<String, Integer> treeMap = new TreeMap<>(map);
        for (Map.Entry<String, Integer> entry : treeMap.entrySet()) {
            System.out.println("\"" + entry.getKey() + "\"" + " : " + entry.getValue());
        }
    }
}
未对 Key 进行排序:
"aac" : 192
"abc" : 122
"dsa" : 12
"bsh" : 232
-----------------------------
使用 Collections.sort 对 Key 进行排序:
"aac" : 192
"abc" : 122
"bsh" : 232
"dsa" : 12
-----------------------------
使用 TreeMap 对 Key 进行排序:
"aac" : 192
"abc" : 122
"bsh" : 232
"dsa" : 12

Process finished with exit code 0

根据 Value 对 Map 进行排序

Here’s a generic-friendly version you’re free to use:

import java.util.*;

public class MapUtil {
    public static <K, V extends Comparable<? super V>> Map<K, V> 
        sortByValue(Map<K, V> map) {
        List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());
        Collections.sort( list, new Comparator<Map.Entry<K, V>>() {
            public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
                return (o1.getValue()).compareTo( o2.getValue() );
            }
        });

        Map<K, V> result = new LinkedHashMap<K, V>();
        for (Map.Entry<K, V> entry : list) {
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }
}

And an associated JUnit4 test so you don’t have to take my word for it:

import java.util.*;
import org.junit.*;

public class MapUtilTest {
    @Test
    public void testSortByValue() {
        Random random = new Random(System.currentTimeMillis());
        Map<String, Integer> testMap = new HashMap<String, Integer>(1000);
        for(int i = 0; i < 1000; ++i) {
            testMap.put( "SomeString" + random.nextInt(), random.nextInt());
        }

        testMap = MapUtil.sortByValue(testMap);
        Assert.assertEquals(1000, testMap.size());

        Integer previous = null;
        for(Map.Entry<String, Integer> entry : testMap.entrySet()) {
            Assert.assertNotNull(entry.getValue());
            if (previous != null) {
                Assert.assertTrue(entry.getValue() >= previous);
            }
            previous = entry.getValue();
        }
    }
}

Java 7 Version

public static <K, V extends Comparable<? super V>> Map<K, V> 
    sortByValue(Map<K, V> map) {
    List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
    Collections.sort( list, new Comparator<Map.Entry<K, V>>() {
        @Override
        public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
            return (o1.getValue()).compareTo(o2.getValue());
        }
    });

    Map<K, V> result = new LinkedHashMap<>();
    for (Map.Entry<K, V> entry : list) {
        result.put(entry.getKey(), entry.getValue());
    }
    return result;
}

Java 8 Version. This will sort according to the value in ascending order; for descending order, it is just possible to uncomment the call to Collections.reverseOrder().

public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
    return map.entrySet()
              .stream()
              .sorted(Map.Entry.comparingByValue(/*Collections.reverseOrder()*/))
              .collect(Collectors.toMap(
                Map.Entry::getKey, 
                Map.Entry::getValue, 
                (e1, e2) -> e1, 
                LinkedHashMap::new
              ));
}

There is one more technique to sort HashMap by Values. Here, no Comparator is used. We do sort based on Keys, swap keys and values, sort based on values and again swap to get the finalMap, which is sorted HashMap based on Values.

 private static LinkedHashMap<String, String> method1(HashMap<String, String> originalHashMap) {
        LinkedHashMap<String, String> sortedHashMapByKeys = new LinkedHashMap<>(); //maintains the order of putting
        TreeMap<String, String> originalTreeMap = new TreeMap<>(originalHashMap); //sorts based on keys
        for (Map.Entry<String, String> map: originalTreeMap.entrySet()) {
            sortedHashMapByKeys.put(map.getKey(), map.getValue());
        }

        LinkedHashMap<String, String> reversedOfSortedLinkedHashMap = new LinkedHashMap<>();
        for (Map.Entry<String, String> map: sortedHashMapByKeys.entrySet()) {
            reversedOfSortedLinkedHashMap.put(map.getValue(), map.getKey());
        }

        LinkedHashMap<String, String> finalMap = new LinkedHashMap<>();
        TreeMap<String, String> treeMapOfReversedOfSortedLinkedHashMap = new TreeMap<>(reversedOfSortedLinkedHashMap);
        for (Map.Entry<String, String> map: treeMapOfReversedOfSortedLinkedHashMap.entrySet()) {
            finalMap.put(map.getKey(), map.getValue()); //sort and swap
        }
        return finalMap;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值