1. 程式人生 > 其它 >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);