Sort Map by value in Ascending and descending order by implementing Comparator interface and overriding its compare method in java


In this Collection framework tutorial we will learn how to sort Map by value in Ascending and descending order (by implementing Comparator interface) with lots of examples and programs in java.



Contents of page :
  • Logic to Sort Map by value in Ascending order

  • Example/Program 1 to Sort Map by value in Ascending order by implementing Comparator interface and overriding its compare method in java

  • Example/Program 2 to Sort Map by value in Descending order by implementing Comparator interface and overriding its compare method in java


Logic to Sort Map by value in Ascending order in java
Implement Comparator interface and override its compare method.
Obtain map.entrySet() in set, convert it into list (we have converted set to list because Collections’s sort method can accept only list type as parameter).
Call Collections.sort and pass list [i.e. listOfentrySet] as parameter.
Collections.sort internally calls Arrays.sort,
Arrays.Sort() internally uses Merge Sort.
Merge sort calls overridden compare method of Comparator interface for comparison of values.
Ultimately listOfentrySet will contain entry (key-value) pairs sorted on basis of values.


Must know fact :
If number of elements is less than 7 then Insertion Sort is used rather than Merge Sort. (because in case elements are less than 7 it offers better time complexity)



Example/Program 1 to Sort Map by value in Ascending order by implementing Comparator interface and overriding its compare method in java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;


class SortByValue implements Comparator<Map.Entry<Integer, Integer>>{
   @Override
   public int compare( Map.Entry<Integer,Integer> entry1, Map.Entry<Integer,Integer> entry2){
       return (entry1.getValue()).compareTo( entry2.getValue() );
   }
}



/**
* @author AnkitMittal
* Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class
*/
public class SortMapByValueAscendingExample {
   public static void main(String...a){
       Mapx<Integer, Integer> map = new HashMap<Integer, Integer>();
       map.put(1, 2);
       map.put(2, 1);
       map.put(3, 9);
       map.put(4, 8);
    
       Set<Entry<Integer, Integer>> entrySet = map.entrySet();
       List<Entry<Integer, Integer>> listOfentrySet = new ArrayList<Entry<Integer, Integer>>(entrySet);
  
       System.out.print("Before sorting by value: ");
       for(Map.Entry<Integer, Integer> entry:listOfentrySet){
        System.out.print(entry.getKey()+"="+entry.getValue()+"  ");
       }
      
      
       Collections.sort(listOfentrySet, new SortByValue());
      
       System.out.print("\nAfter sorting by value(ascending): ");
       for(Map.Entry<Integer, Integer> entry:listOfentrySet)
        System.out.print(entry.getKey()+"="+entry.getValue()+"  ");
      
      
   }
}
/*OUTPUT
Before sorting by value: 1=2  2=1  3=9  4=8
After sorting by value(ascending): 2=1  1=2  4=8  3=9
*/
Note : In the above program, only listOfentrySet obtained from map contain entry (key-value) pairs sorted on basis of values, map is not sorted on basis of values.



Example/Program 2 to Sort Map by value in Descending order by implementing Comparator interface and overriding its compare method in java
In the above program replace SortByValue class with below SortByValue class in java.
class SortByValue implements Comparator<Map.Entry<Integer, Integer>>{
  @Override
  public int compare( Map.Entry<Integer,Integer> entry1, Map.Entry<Integer,Integer> entry2){
       return (entry2.getValue()).compareTo( entry1.getValue() );
  }
}

OUTPUT will be >
/*OUTPUT
Before sorting by value: 1=2  2=1  3=9  4=8
After sorting by value(descending): 3=9  4=8  1=2  2=1
*/


So in this Collection framework tutorial we learned how to sort Map by value in Ascending and descending order (by implementing Comparator interface) with lots of examples and programs in java.



Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.


RELATED LINKS>

Collection in java


Map hierarchy in java - Detailed - HashMap, Hashtable, ConcurrentHashMap, LinkedHashMap, TreeMap, ConcurrentSkipListMap, IdentityHashMap, WeakHashMap, EnumMap classes


Sorting Collection by implementing comparator and Comparable, using TreeMap and TreeSet, Collections.sort and Arrays.sort >

Comparable vs Comparator - differences and sorting list by implementing Comparable and Comparator in classes and inner classes


Arrays.sort to sort arrays by implementing Comparator and how Comparator of superclass can be used by subclasses


Sort Set by using TreeSet and by implementing Comparator and Comparable interface


Sort Map by key in Ascending and descending order by implementing Comparator interface and overriding its compare method and using TreeMap




No comments:

Post a Comment