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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With