Program to Sort Map by key in Descending order by implementing Comparator interface and overriding its compare method







In the previous program replace SortByKeyAscending class with below SortByKeyDescending class.




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

OUTPUT will be >
/*OUTPUT
Before sorting by key : 4=1  2=1  3=1  5=1
After sorting by key(descending) : 5=1  4=1  3=1  2=1
*/

Full program >
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
class SortByKeyDescending implements Comparator<Map.Entry<Integer, Integer>>{
   @Override
  public int compare( Map.Entry<Integer, Integer> entry1, Map.Entry<Integer, Integer> entry2 ){
       return (entry2.getKey()).compareTo( entry1.getKey() );
  }
}
/**
* @author AnkitMittal
* Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class
*/
public class SortMapByKeyDescending {
   public static void main(String...a){
       Map<Integer, Integer> map = new LinkedHashMap<Integer, Integer>();
       map.put(4, 1);
       map.put(2, 1);
       map.put(3, 1);
       map.put(5, 1);
      
       Set<Entry<Integer, Integer>> entrySet = map.entrySet();
       List<Entry<Integer, Integer>> listOfentrySet = new ArrayList<Entry<Integer, Integer>>(entrySet);
  
       System.out.print("Before sorting by key : ");
       for(Map.Entry<Integer, Integer> entry:listOfentrySet){
        System.out.print(entry.getKey()+"="+entry.getValue()+"  ");
       }
      
       Collections.sort(listOfentrySet, new SortByKeyDescending());
      
       System.out.print("\nAfter sorting by key(descending) : ");
       for(Map.Entry<Integer, Integer> entry:listOfentrySet)
        System.out.print(entry.getKey()+"="+entry.getValue()+"  ");
      
      
   }
}
/*OUTPUT
Before sorting by key : 4=1  2=1  3=1  5=1
After sorting by key(descending) : 5=1  4=1  3=1  2=1
*/

No comments:

Post a Comment