java 中对Map<String, Object>的value 排序

2022/5/12 17:27:22

本文主要是介绍java 中对Map<String, Object>的value 排序,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

创建 map 对象:

 Map<String, Object> map = new HashMap<>();
        /*{key, value}*/
        map.put("张三", 34);
        map.put("张三老婆", 27);
        map.put("张三爸爸", 64);
        map.put("张三妈妈", 58);
        map.put("张三妹妹", 21);

        System.out.println(" 没有排序前: ");
        System.out.println(map);
Set<Map.Entry<String, Object>> set = map.entrySet();

 方法1:

 System.out.println("\n 方法1: ");
        System.out.println(" 按value升序排:  ");
        ArrayList<Map.Entry<String, Object>> list1 = new ArrayList<>(set);
        Collections.sort(list1, new Comparator<Map.Entry<String, Object>>() {
            @Override
            public int compare(Map.Entry<String, Object> o1, Map.Entry<String, Object> o2) {
                return (Integer.parseInt(o1.getValue().toString()) - Integer.parseInt(o2.getValue().toString()));
            }
        });
        System.out.println(list1);

        System.out.println(" 按value倒序排");
        Collections.sort(list1, new Comparator<Map.Entry<String, Object>>() {
            @Override
            public int compare(Map.Entry<String, Object> o1, Map.Entry<String, Object> o2) {
                return Integer.parseInt(o2.getValue().toString()) - Integer.parseInt(o1.getValue().toString());
            }
        });
        System.out.println(list1);

方法2:

System.out.println("\n 方法2: ");
        ArrayList<Map.Entry<String, Object>> list2 = new ArrayList<>(set);
        System.out.println(" 按value升序排");
        Collections.sort(list2, (o1, o2) -> (Integer)o1.getValue() - (Integer)o2.getValue());
        System.out.println(list2);

        System.out.println(" 对value降序排");
        Collections.sort(list2, (o1, o2) -> (Integer)o2.getValue() - (Integer)o1.getValue());
        System.out.println(list2);

方法3:

System.out.println("\n 方法3: ");
        ArrayList<Map.Entry<String, Object>> list3 = new ArrayList<>(set);
        System.out.println(" 按value升序排");
        Collections.sort(list3, Test2::compareAsc);
        System.out.println(list3);

        System.out.println(" 对value降序排");
        Collections.sort(list3, Test2::compareDesc);
        System.out.println(list3);

方法4:

 System.out.println("\n  方法4: ");
        System.out.println(" 按value升序排");
        List<Map.Entry<String, Object>> collect = set.stream().sorted(Comparator.comparing(o -> (Integer) o.getValue())).collect(Collectors.toList());
        System.out.println(collect);

  

 



这篇关于java 中对Map<String, Object>的value 排序的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程