How to use a Comparator with a TreeMap in Java? | Sololearn: Learn to code for FREE!


How to use a Comparator with a TreeMap in Java?

I have a TreeMap that I want to sort by increasing or decreasing values. How?

3/30/2020 8:08:46 AM

chris elo

4 Answers

New Answer


Not really, set removes duplicates. import java.util.*; public class Program { public static void main(String[] args) { boolean ascending = false; SortedMap<String, String> sortedmap = new TreeMap<String, String>(ascending ? Comparator.naturalOrder() : Comparator.reverseOrder()); sortedmap.put("a", "t"); sortedmap.put("b", "b"); sortedmap.put("c", "t"); sortedmap.put("d", "s"); sortedmap.put("e", "x"); System.out.println(sortedmap); } } Would this solution satisfy you? Btw, just for the clarification purpose, do you want to sort your collection by key or value? - this thread might contain the answer to your question. Seems like Comparators should be used only for keys.



Will this work, if some values are equal?


Ok thanks