小工具知识网

当前位置: 首页 > 行业知识 > Java对Map 通过value值进行排序

行业知识

Java对Map 通过value值进行排序

2026-10-26 16:32:00 来源:互联网转载

1、Java 8 使用AbacusUtil实现

AbacusUtil:

()
Map map = N.asMap("a", 2, "b", 3, "c", 1, "d", 2);Map sortedMap = Stream.of(map.entrySet()).sorted(Map.Entry.comparingByValue()).toMap(e -> e.getKey(), e -> e.getValue(),    LinkedHashMap::new);N.println(sortedMap);// output: {c=1, a=2, d=2, b=3}

2、使用for循环实现

public class Test  {    public static void main(String[] args)  {        HashMap hashMap = new HashMap();        hashMap.put("Cat", (long) 4);        hashMap.put("Human", (long) 2);        hashMap.put("Dog", (long) 4);        hashMap.put("Fish", (long) 0);        hashMap.put("Tree", (long) 1);        hashMap.put("Three-legged-human", (long) 3);        hashMap.put("Monkey", (long) 2);        System.out.println(hashMap);  //{Human=2, Cat=4, Three-legged-human=3, Monkey=2, Fish=0, Tree=1, Dog=4}        System.out.println(sortHashMap(hashMap));  //{Cat=4, Dog=4, Three-legged-human=3, Human=2, Monkey=2, Tree=1, Fish=0}    }    public LinkedHashMap sortHashMap(HashMap unsortedMap)  {        LinkedHashMap result = new LinkedHashMap();        //add String keys to an array: the array would get sorted, based on those keys' values        ArrayList sortedKeys = new ArrayList();        for (String key: unsortedMap.keySet())  {            sortedKeys.add(key);        }        //sort the ArrayList of keys            for (int i=0; i            for (int j=1; j                if (unsortedMap.get(sortedKeys.get(j))  unsortedMap.get(sortedKeys.get(j-1))) {                    String temp = sortedKeys.get(j);                    sortedKeys.set(j, sortedKeys.get(j-1));                    sortedKeys.set(j-1, temp);                }            }        }        // construct the result Map        for (String key: sortedKeys)  {            result.put(key, unsortedMap.get(key));        }        return result;    }}
h33、使用stream()实现/h3 pre MapK, V sindex.php/tags-1038.html" >ortedMap = map.entrySet().stream() .sorted(Entry.comparingByValue()) .collect(Collectors.toMap(Entry::getKey, Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));

4、使用ArrayList排序实现

public class MapUtil {    public static 

上一篇:Win10专业版安装指南,轻松上手,一步到位的详细教程!

下一篇:源码级深度解析,揭秘条码管理的奥秘与核心机制