编程语言
首页 > 编程语言> > java 中对Map<String, Object>的value 排序

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);

  

 

标签:Map,java,map,System,value,getValue,println,Integer,out
来源: https://www.cnblogs.com/dayu33/p/16262979.html