HashMap 정렬

: ) YOUNG·2025년 2월 10일
1

알고리즘

목록 보기
449/458

value기준 오름차순 정렬


        HashMap<String, Integer> map = new HashMap<>();
        map.put("a", 110);
        map.put("b", 109);
        map.put("c", 108);
        map.put("d", 107);
        map.put("e", 106);

        List<Map.Entry<String, Integer>> entryList = new ArrayList<>(map.entrySet());
        System.out.println(entryList);
        // [a=110, b=109, c=108, d=107, e=106]

        // value 낮은순으로 정렬
        Collections.sort(entryList, (o1, o2) -> {
            return o1.getValue().compareTo(o2.getValue());
        });
        System.out.println(entryList);
        // [e=106, d=107, c=108, b=109, a=110]

        LinkedHashMap<String, Integer> sortedMap = new LinkedHashMap<>();
        for (Map.Entry<String, Integer> entry : entryList) {
            sortedMap.put(entry.getKey(), entry.getValue());
        }

        System.out.println("sortedMap : " + sortedMap);
        // sortedMap : {e=106, d=107, c=108, b=109, a=110}

0개의 댓글

관련 채용 정보