Disclosure: This article may contain affiliate links. When you purchase, we may earn a commission.

Thursday, January 12, 2023

What is TreeMap in Java? HashMap vs TreeMap Example Tutorial

Hello guys, I hope you all are doing well and having lots of fun reading and learning Java Collections together. Today we are here a meet again on our journey of Java. I hope you all have seatbelts buckled up as today it's gonna be an adventurous ride while learning something that is most used in many production applications, coding, and whatnot. Today's topic, TreeMap in Java is very important because it holds a very significant feature Java development kit provides. This is also one class which many Java developer doesn't pay attention but it is really used for many use cases. Most Java developer just keep their attention to ArrayList, HashSet, and HashMap and thus missing out on many cool Java collection classes like TreeMap, WeakHashMap, and LinkedHashMap which saw earlier.

TreeMap is a special class that allows you to store key-value pairs in sorted order by keys. This means you can store numeric keys in increasing or decreasing order as well as string keys in alphabetic or alphanumeric order. You can even store objects in the order defined by their Comparator and Comparable implementation.

I have often used TreeMap to store object in priority. This is also key to process elements in order, for example, you may want to process orders coming into exchange based upon their time and price priority. I have used TreeMap in past on such situation where Limit orders are sorted based upon their price. 

So, what's the wait? Let's start!
As usual, let's start with a scenario (yeah, I will never stop with scenarios :p). I suppose you guys are familiar with HashMap. Because today's topic is solely dependent on your knowledge of HashMap.

You guys can have a look at the HashMap article, which we previously covered. We will still give a gist of that here in a paragraph so that you guys can recall it.

1. What is HashMap in Java

The Java HashMap implementation of the Map interface is based on hash tables. A Map is a set of key-value pairs, as you may know. It converts keys into values.
  • There can't be any duplicate keys in a HashMap.
  • Null values and the null key are allowed in Java HashMap.
  • HashMap is a collection that is not in any particular order. It does not ensure that the elements will be in any particular sequence.
  • HashMap in Java is not thread-safe. You must explicitly synchronize concurrent HashMap changes.

HashMap is declared as:

Map<String, Integer> map = new HashMap<>();

Now, after you guys know what HashMap is and How HashMap works, let's jump into today's topic with a scenario.

Let's say we have a HashMap with us. The HashMap has a String key type, and the value type is Integer. Let's say we have unique car names as key, and value is the max speed limit of the cars.

So, the HashMap would look like this:

 Map<String,Integer> carMap = new HashMap<>();   

The values inside the map would be similar to this: {'BMW m3' - 360, 'Audi a6 - 340', 'Mercedes q3 - 320', 'Bugatti Veyron - 420'}. This represents the {'key' - value} notation. Each key is linked to its value. 

Now, let's say we have a requirement such as a user is presented with a list of cars and their top speed, and the user wants to sort the list according to car names. What will you do in this case?

Think for 2 minutes, and then we will discuss the possible solutions. (There are multiple solutions to this problem, but we will focus on one that the article is about.)

One way is to get a copy of all the keys into a list and then sort the list. This way, we can get the keys sorted in the natural order and get the value from the HashMap in O(1) time. Pretty cool, right? Wait till you use a more cool feature of Java. Let me introduce you to something incredible!

2. What is TreeMap in Java

Along with the AbstractMap Class, Java's TreeMap is utilized to implement the Map interface and NavigableMap. Depending on whether function Object() { [native code] } is used, the map is sorted either by the natural ordering of its keys or by a Comparator given at map construction time. 

This is a time-saving method of sorting and storing key-value pairs. Regardless of the specified comparators, the TreeMap's storage order must be consistent with equals, just like any other sorted map. 

The TreeMap implementation is not synchronized in the sense that a map must be synchronized externally, if it is used by several threads concurrently, and at least one of the threads alters the map structurally.

How to use TreeMap in Java? Example Tutorial

Let's see a working code of TreeMap and how it sorts the keys in its natural order.


import java.util.Map;
import java.util.TreeMap;

public class MyMap {
public static void main(String[] args) {
Map<String, Integer> map = new TreeMap<>();
map.put("BMW M3", 360);
map.put("Audi A6", 340);
map.put("Mercedes Q3", 320);
map.put("Buggati Veyron", 420);

map.forEach((key, value) -> System.out.println(key + " --> " + value));



How to use TreeMap in Java? Example Tutorial

Now, as you all can observe the output, sort the keys in the natural order. Now, before using it, let's see some of the essential points of TreeMap.

3. TreeMap Properties 

Here are some essential points about TreeMap which every Java programmer should remember:
  • The key determines the values in a Java TreeMap. 
  • It extends the AbstractMap class and implements the NavigableMap interface.
  • Only unique items are found in the Java TreeMap.
  • There can't be a null key in a Java TreeMap, but many null values may be.
  • TreeMap in Java is not synchronized.
  • Ascending order is maintained via Java TreeMap.  

Also, the declaration of how Java does for TreeMap is something like this: 

public class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V>, Cloneable, Serializable 

The parameters in this declaration are as follows: 

  • K: It is the type of keys maintained by this map.
  • V: It is the type of mapped values.

Here is also the type hierarchy of TreeMap in Java, you can see that its both SortedMap as well as NavigableMap

How to use TreeMap in Java? Example Tutorial

That's all about how and when to use TreeMap in Java. It's an important class because it allows you to keep key-value mapping in order. Particularly keys are stored in order and follow the order specified by Comparator or natural order defined by Comparable. 

TreeMap is also a NavigableMap which means you can get the lowest and highest entries and get entries in a range. All these properties make TreeMap an instrumental class for Java application development. 

Hope you guys are now in absolute love with TreeMap. Please also try to perform some Hand-on and get a go with TreeMap.

Other Java Collection and Map tutorials  you may like
  • How does the get() method of HashMap work in Java? (answer)
  • Difference between HashMap and Hashtable in Java? (answer)
  • Difference between ConcurrentHashMap and HashMap in Java? (answer)
  • How HashSet internally works in Java? (answer)
  • How ConcurrentHashMap internally works in Java? (answer)
  • Difference between HashSet and HashMap in Java? (answer)
  • Difference between HashMap and LinkedHashMap in Java? (answer)
  • The best way to iterate over HashMap in Java? (answer)
  • Difference between ArrayList and HashMap in Java? (answer)
  • How to sort the HashMap on keys and values in Java? (solution)
  • 3 ways to loop over a Map in Java? (example)
  • The difference between HashMap and ConcurrentHashMap in Java? (answer)
  • What is the difference between ArrayList and HashMap? (difference)
  • How to convert Map to List in Java? (solution)

Thanks for reading this article so far. If you like this Java TreeMap tutorial and Example then please share with your friends and colleagues. If you have any questions or feedback, please ask in comments.

P. S. - If you are new to Java and want to learn Java in depth, you can also checkout these 10 Free Core Java Courses to start with. It contains best free Java courses from Udemy and Coursera for beginners. 

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.