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





In the previous program replace SortByValue class with below SortByValue class.



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
*/

Full program >

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 (entry2.getValue()).compareTo( entry1.getValue() );
  }
}
/**
* @author AnkitMittal
* Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class
*/
public class SortMapByValueDescending {
   public static void main(String...a){
       Map<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>> set = map.entrySet();
       List<Entry<Integer, Integer>> list = new ArrayList<Entry<Integer, Integer>>(set);
  
       System.out.print("Before sorting by value: ");
       for(Map.Entry<Integer, Integer> entry:list){
        System.out.print(entry.getKey()+"="+entry.getValue()+"  ");
       }
      
      
       Collections.sort(list, new SortByValue());
      
       System.out.print("\nAfter sorting by value(descending): ");
       for(Map.Entry<Integer, Integer> entry:list)
        System.out.print(entry.getKey()+"="+entry.getValue()+"  ");
      
      
   }
}
/*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
*/



RELATED LINKS>

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


No comments:

Post a Comment