Java 8 – Sorted Map By Key & Value

Posted on

Java-8

 

 

 

Below example will show, how to sort Collection & Map element by Key & Value using Lambda Expression in Java 8.

Example 1

In this example, we will see how to sort  element of Collection using Lambda expression.


        List listOfString = new ArrayList<>();
        listOfString.add("Z");
        listOfString.add("Q");
        listOfString.add("D");
        listOfString.add("A");
        listOfString.add("H");
        listOfString.add("T");

        listOfString.stream().sorted((e1,e2)->e1.compareTo(e2)).forEach(e->{
            System.out.println(" sorted list of String "+e);
        });
        // return new sorted list.
        /*        
        listOfString = listOfString.stream()
                                   .sorted((e1,e2)->e1.compareTo(e2))
                                   .collect(Collectors.toList());
        listOfString.forEach(e->{
            System.out.println(" sorted list of String "+e);
        });*/

Output:-
sorted list of String A
sorted list of String D
sorted list of String H
sorted list of String Q
sorted list of String T
sorted list of String Z

Example 2 : See how to sort a List’s Person by Name.

 


        List list = new ArrayList();

        list.add(new Person(6, "FF", 13, Person.SEX.MALE, "GOA"));
        list.add(new Person(7, "GG", 31, Person.SEX.FEMALE, "Delhi"));
        list.add(new Person(8, "HH", 30, Person.SEX.MALE, "Mumbai"));
        list.add(new Person(9, "II", 22, Person.SEX.FEMALE, "Delhi"));
        list.add(new Person(1, "AA", 12, Person.SEX.FEMALE, "Delhi"));
        list.add(new Person(2, "BB", 22, Person.SEX.FEMALE, "MP"));
        list.add(new Person(3, "CC", 44, Person.SEX.FEMALE,"UP"));
        list.add(new Person(4, "DD", 25, Person.SEX.MALE, "Gurgaon"));
        list.add(new Person(5, "EE", 51, Person.SEX.FEMALE, "GOA"));

         // sorted Person by name
        List sortedList = list.stream()
                .sorted((p1,p2)->p1.getName().compareTo(p2.getName()))
                .collect(Collectors.toList());
        sortedList.forEach(p->System.out.println("sorted by name :: "+p.toString()));


output :-
sorted by name :: Person{id=1, name=’AA’, age=12, gender=FEMALE, location=’Delhi’}
sorted by name :: Person{id=2, name=’BB’, age=22, gender=FEMALE, location=’MP’}
sorted by name :: Person{id=3, name=’CC’, age=44, gender=FEMALE, location=’UP’}
sorted by name :: Person{id=4, name=’DD’, age=25, gender=MALE, location=’Gurgaon’}
sorted by name :: Person{id=5, name=’EE’, age=51, gender=FEMALE, location=’GOA’}
sorted by name :: Person{id=6, name=’FF’, age=13, gender=MALE, location=’GOA’}
sorted by name :: Person{id=7, name=’GG’, age=31, gender=FEMALE, location=’Delhi’}
sorted by name :: Person{id=8, name=’HH’, age=30, gender=MALE, location=’Mumbai’}
sorted by name :: Person{id=9, name=’II’, age=22, gender=FEMALE, location=’Delhi’}

Example 3:- See how to sort a Map by value element


        //Sort a Map by their Value.
        Map<Integer, String> random = new HashMap<Integer, String>();
       
        random.put(1,"z");
        random.put(6,"k");
        random.put(5,"a");
        random.put(3,"f");
        random.put(9,"c");

        Map<Integer, String> sortedMap =
                random.entrySet().stream()
                        .sorted(Map.Entry.comparingByValue())
                        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                                (e1, e2) -> e2, LinkedHashMap::new));
        System.out.println("Sorted Map: " + Arrays.toString(sortedMap.entrySet().toArray()));

Output :-
Sorted Map: [5=a, 9=c, 3=f, 6=k, 1=z]

Example 4:- See how to sort a Map by Key element


        //Sort a Map by their Key.
        Map<Integer, String> random = new HashMap<Integer, String>();
       
        random.put(1,"z");
        random.put(6,"k");
        random.put(5,"a");
        random.put(3,"f");
        random.put(9,"c");

        Map<Integer, String> sortedMap =
                random.entrySet().stream()
                        .sorted(Map.Entry.comparingByKey())
                        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                                (e1, e2) -> e2, LinkedHashMap::new));
        System.out.println("Sorted Map: " + Arrays.toString(sortedMap.entrySet().toArray()));

Output :-
Sorted Map: [1=z, 3=f, 5=a, 6=k, 9=c]

Example 5:-

Here, A Map<String,Person> is created where String & Person object are taken as a Key & Value elements. First we will sort by Key elements then sort by Value elements in this below example.

Sorted by Map’s Key –


        Map<String,Person> map = new HashMap<>();
        map.put("g",new Person(5, "EE", 51, Person.SEX.FEMALE, "A"));
        map.put("a",new Person(4, "DD", 25, Person.SEX.MALE, "D"));
        map.put("e",new Person(3, "CC", 44, Person.SEX.FEMALE,"B"));

        Map<String,Person> sortedNewMap = map.entrySet().stream()
                .sorted((e1,e2)->e1.getKey().compareTo(e2.getKey()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (e1, e2) -> e1, LinkedHashMap::new));
        sortedNewMap.forEach((key,val)->{
            System.out.println(key+ " = "+ val.toString());
        });

Output:- 

a = Person{id=4, name=’DD’, age=25, gender=MALE, location=’D’}
e = Person{id=3, name=’CC’, age=44, gender=FEMALE, location=’B’}
g = Person{id=5, name=’EE’, age=51, gender=FEMALE, location=’A’}

Final output give us a Map which values are sorted location field –


        Map<String,Person> map = new HashMap<>();
        map.put("g",new Person(5, "EE", 51, Person.SEX.FEMALE, "A"));
        map.put("a",new Person(4, "DD", 25, Person.SEX.MALE, "D"));
        map.put("e",new Person(3, "CC", 44, Person.SEX.FEMALE,"B"));

        Map<String,Person> sortedNewMap = map.entrySet().stream().sorted((e1,e2)->
                e1.getValue().getLocation().compareTo(e2.getValue().getLocation()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (e1, e2) -> e1, LinkedHashMap::new));
        sortedNewMap.forEach((key,val)->{
            System.out.println(key+ " = "+ val.toString());
        });

Output:- 
g = Person{id=5, name=’EE’, age=51, gender=FEMALE, location=’A’}
e = Person{id=3, name=’CC’, age=44, gender=FEMALE, location=’B’}
a = Person{id=4, name=’DD’, age=25, gender=MALE, location=’D’}

 

There are lots of ways to do this work depends on the requirement. Hope you enjoy this post.
Thanks
——–
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s