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

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?

3/30/2020 8:08:46 AM

chris elo

4 Answers

New Answer

+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.

0

https://code.sololearn.com/cwsSlxW4scge/?ref=app https://stackoverflow.com/questions/12947088/java-treemap-comparator

0

Will this work, if some values are equal?

0

Ok thanks