Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why and when to use TreeMap [closed]

Tags:

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.

like image 583
Java_Alert Avatar asked Dec 07 '12 11:12

Java_Alert


People also ask

When should treemap be used?

Treemaps are often used for sales data, as they capture relative sizes of data categories, allowing for quick perception of the items that are large contributors to each category. Color can identify items that are underperforming (or overperforming) compared to their siblings from the same category.

What are the advantages of using a treemap?

Advantages of Treemap ChartsUtilization of space when rendering tens of thousands of data points, with the ability to drill down as needed. Accurately displaying multiple elements at once, including “part to whole” ratios. This makes visualization of data easy. Uses size and color keys to visualize various attributes.

Why would anyone use treemap over HashMap when they don't care about ordering?

A Treemap can save memory (in comparison to HashMap) because it only uses the amount of memory needed to hold its items, unlike a HashMap which uses contiguous region of memory.

When would a treemap be preferable to a HashMap?

It provides a performance of O(1) , while TreeMap provides a performance of O(log(n)) to add, search, and remove items. Hence, HashMap is usually faster. A TreeMap uses memory way more effective so it is a good Map implementation for you if you are not sure of elements quantity that have to be stored in memory.


1 Answers

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.

like image 85
assylias Avatar answered Sep 27 '22 01:09

assylias