Try using the code below, it works fine and based on the order flag will be sorted in ascending or descending order.
import java.util.Comparator; import java.util.Map; import java.util.TreeMap; public class HelloWorld { public static void main(String[] args) { final boolean order = true; try { Map<Integer, String> map = new TreeMap<Integer, String>( new Comparator<Integer>() { @Override public int compare(Integer first, Integer second) { if (order) { return second.compareTo(first); } else { return first.compareTo(second); } } }); map.put(2, "v"); map.put(3, "h"); map.put(4, "e"); map.put(1, "a"); System.out.println(map); } catch (Exception e) { e.printStackTrace(); } } }
source share