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

 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>{    @Override    public int compare( Map.Entry entry1, Map.Entry entry2){        return (entry1.getValue()).compareTo( entry2.getValue() );    } } /** * @author AnkitMittal * Copyright (c), AnkitMittal JavaMadeSoEasy.com * Main class */ public class SortMapByValueAscending {    public static void main(String...a){        Mapx map = new HashMap();        map.put(1, 2);        map.put(2, 1);        map.put(3, 9);        map.put(4, 8);             Set> entrySet = map.entrySet();        List> listOfentrySet = new ArrayList>(entrySet);           System.out.print("Before sorting by value: ");        for(Map.Entry 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 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.