how to sort map by value.




      






This   example   explain   how  you    sort   map by  key  using   java8  . Using  java 8  we
   do   following  steps 



1. Convert a Map into a Stream
2. Sort it
3. Collect and return a new LinkedHashMap (keep the order)

    example  follows  same  steps    coding  as   which  explain  below. 




package Java8;


import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class SortMapByValue {

    public static void main(String[] args) {

        Map<String, Integer> unsortMap = new HashMap<>();
        unsortMap.put("z", 10);
        unsortMap.put("b", 5);
        unsortMap.put("r", 6);
        unsortMap.put("a", 20);
        unsortMap.put("d", 1);
        unsortMap.put("e", 7);
        unsortMap.put("y", 8);
        unsortMap.put("n", 99);
        unsortMap.put("g", 50);
        unsortMap.put("m", 2);
        unsortMap.put("f", 9);
        unsortMap.put("a", 6);

        System.out.println("Original...");
        System.out.println(unsortMap);

        //sort by values, and reserve it, 10,9,8,7,6...

        Map<String, Integer> result = unsortMap.entrySet().stream()

                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))

                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,

                        (oldValue, newValue) -> oldValue, LinkedHashMap::new));

        //Alternative way
        Map<String, Integer> result2 = new LinkedHashMap<>();

        unsortMap.entrySet().stream()

                .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())

                .forEachOrdered(x -> result2.put(x.getKey(), x.getValue()));

        System.out.println("Sorted...");
        System.out.println(result);
        System.out.println( "Another way of sorting");

        System.out.println(result2);

    }
}


Output :----
Original...
{a=6, b=5, r=6, d=1, e=7, f=9, g=50, y=8, z=10, m=2, n=99}
Sorted...
{n=99, g=50, z=10, f=9, y=8, e=7, a=6, r=6, b=5, m=2, d=1}
Another way of sorting

{n=99, g=50, z=10, f=9, y=8, e=7, a=6, r=6, b=5, m=2, d=1}


how to sort map by value. how to sort   map   by value. Reviewed by Mukesh Jha on 8:27 PM Rating: 5

No comments:

Add your comment

All Right Reserved To Mukesh Jha.. Theme images by Jason Morrow. Powered by Blogger.