Why and when to use TreeMap

Java_Alert picture Java_Alert · Dec 7, 2012 · Viewed 32.7k times · Source

Could someone tell me when and why to use TREEMAP.I went through This link but didn't find my answer.

As Per my thinking we use treemap to get the data sort according to your key and the same we can achieve by other ways also.

Answer

assylias picture assylias · Dec 7, 2012

Let's say you want to implement a dictionary and print it in alphabetical order, you can use a combination of a TreeMap and a TreeSet:

public static void main(String args[]) {
    Map<String, Set<String>> dictionary = new TreeMap<>();
    Set<String> a = new TreeSet<>(Arrays.asList("Actual", "Arrival", "Actuary"));
    Set<String> b = new TreeSet<>(Arrays.asList("Bump", "Bravo", "Basic"));

    dictionary.put("B", b);
    dictionary.put("A", a);

    System.out.println(dictionary);
}

All the sorting is done automatically and it prints:

{A=[Actual, Actuary, Arrival], B=[Basic, Bravo, Bump]}

You could have sorted the structures manually too of course but using TreeMap/Set can be more efficient, reduces the number of lines of code (= the number of bugs) and is more readable.