We are moved to new domain
Click -> www.ehowtonow.com
Friday, 21 July 2017

Java 8 - Sort Map by Value

In this article we are going to see about Java 8 - How to Sort map by value Example

Java8SortMap.java

package com.javatutorialcorner.java8;

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

public class Java8SortMap {

 public static void main(String[] args) {
  Map batsmanRanking = new HashMap();
  batsmanRanking.put("Virat Kohli", 1);
  batsmanRanking.put("AB de Villiers", 2);
  batsmanRanking.put("David Warner", 3);
  batsmanRanking.put("Joe Root", 4);
  batsmanRanking.put("Kane Williamson", 5);
  batsmanRanking.put("Quinton de Kock", 6);
  batsmanRanking.put("Faf du Plessis", 7);
  batsmanRanking.put("Babar Azam", 8);
  batsmanRanking.put("Martin Guptill", 9);
  batsmanRanking.put("Shikhar Dhawan", 10);
  
  System.out.println("Unsort Map...");
        System.out.println(batsmanRanking);
        
        //Convert a Map into a Stream
        //Sort it - values, reserve it and return a new LinkedHashMap
        //Collect and return a new LinkedHashMap (keep the order) - 
        //toMap() will returns HashMap by default, we need LinkedHashMap to keep the order.
        Map resultMap1 = batsmanRanking.entrySet().stream()
                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue, LinkedHashMap::new));
        
        Map resultMap2 = new LinkedHashMap<>();
        batsmanRanking.entrySet().stream()
        .sorted(Map.Entry.comparingByValue().reversed())
        .forEachOrdered(x -> resultMap2.put(x.getKey(), x.getValue()));

        System.out.println("Sorted Map 1...");
        System.out.println(resultMap1);
        System.out.println("Sorted Map 2...");
        System.out.println(resultMap2);
 }

}

Output
Unsort Map...
{Faf du Plessis=7, Virat Kohli=1, Martin Guptill=9, Babar Azam=8, Quinton de Kock=6, Kane Williamson=5, AB de Villiers=2, Joe Root=4, David Warner=3, Shikhar Dhawan=10}
Sorted Map 1...
{Shikhar Dhawan=10, Martin Guptill=9, Babar Azam=8, Faf du Plessis=7, Quinton de Kock=6, Kane Williamson=5, Joe Root=4, David Warner=3, AB de Villiers=2, Virat Kohli=1}
Sorted Map 2...
{Shikhar Dhawan=10, Martin Guptill=9, Babar Azam=8, Faf du Plessis=7, Quinton de Kock=6, Kane Williamson=5, Joe Root=4, David Warner=3, AB de Villiers=2, Virat Kohli=1}


Shop and help us

Flipkart Offer Snapdeal offer Amazon.in offer Amazon.com offer
  • Blogger Comments
  • Facebook Comments
  • Disqus Comments

0 comments:

Post a Comment

Item Reviewed: Java 8 - Sort Map by Value Rating: 5 Reviewed By: eHowToNow