Java_Alert
Java_Alert

Reputation: 1179

Why and when to use TreeMap

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.

Upvotes: 31

Views: 43245

Answers (4)

Aleksander Gralak
Aleksander Gralak

Reputation: 1509

It is efficient way of having objects sorted by some key. If also random access is important for you then TreeMap is the answer. With this data structure you can iterate in order.

If random access is not needed then rather use sorted set/bag or list.

Why is there no SortedList in Java?

Upvotes: 9

David Soroko
David Soroko

Reputation: 9086

The javadoc you link to, clearly states that it is an implementation of navigable and sorted map interfaces. You would use it when you need this functionality.

Upvotes: 5

assylias
assylias

Reputation: 328619

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.

Upvotes: 37

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41200

TreeMap

A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.

This implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations. Algorithms are adaptations of those in Cormen, Leiserson, and Rivest's Introduction to Algorithms.

Use this data-structure when you need ordered key not only ascending you can pass comparator to constructor TreeMap(Comparator<? super K> comparator) to write your own sorting logic. As well it is a type of self-balancing binary search tree.

Upvotes: 5

Related Questions