Here is Java Sort Map By Key example and Java Sort Map By Value example:

  1. Java Sort Map By Key Example

java.util.Map<Integer, String> map = new HashMap();
        map.put(1, "Jone");
        map.put(6, "Araya");
        map.put(3, "Boby");
        map.put(8, "Zoo");

        Map<Integer, String> sortedMap = map.entrySet().stream()
                                            .sorted(Comparator
                                                    .comparing(Map.Entry::getKey))             // Sort based on key
                                            .collect(Collectors
                                                    .toMap(Map.Entry::getKey, Map.Entry::getValue, (a1, a2) -> a1, LinkedHashMap::new));      // convert data to LinkedHashMap

        sortedMap.forEach((k, v) -> {
            System.out.println(k + "-" + v);
        });

Output:

1-Jone
3-Boby
6-Araya
8-Zoo

 

  1. Java Sort Map By Value Example

java.util.Map<Integer, String> map = new HashMap();
        map.put(1, "Jone");
        map.put(6, "Araya");
        map.put(3, "Boby");
        map.put(8, "Zoo");

        Map<Integer, String> sortedMap = map.entrySet().stream()
                                            .sorted(Comparator
                                                    .comparing(Map.Entry::getValue))             // Sort based on value
                                            .collect(Collectors
                                                    .toMap(Map.Entry::getKey, Map.Entry::getValue, (a1, a2) -> a1, LinkedHashMap::new));      // convert data to LinkedHashMap

        sortedMap.forEach((k, v) -> {
            System.out.println(v + "-" + k);
        });

Output:

Araya-6
Boby-3
Jone-1
Zoo-8

 

 

 

Was this post helpful?
Let us know, if you liked the post. Only in this way, we can improve us.
Yes
No

Leave a Reply

Your email address will not be published. Required fields are marked *