How to use a Comparator with a TreeMap in Java? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

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?

30th Mar 2020, 8:08 AM
chris elo
chris elo - avatar
4 Answers
+ 1
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? https://stackoverflow.com/questions/12947088/java-treemap-comparator - this thread might contain the answer to your question. Seems like Comparators should be used only for keys.
30th Mar 2020, 11:34 AM
Steppenwolf
Steppenwolf - avatar
0
Will this work, if some values are equal?
30th Mar 2020, 9:41 AM
chris elo
chris elo - avatar
0
Ok thanks
30th Mar 2020, 11:40 AM
chris elo
chris elo - avatar