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?
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.
0
Will this work, if some values are equal?
0
Ok thanks