If you want to save a sequence of key/value pairs and if you want them ordered by the key, what would be your ideal option? Don’t have an idea? Don’t worry. Let’s talk about that today.
Hello coders, I am back with a new article in my Java Collections Framework article series. Today I am going to discuss TreeMap class in Java. TreeMap class extends the SortedMap Interface and that extends the Map Interface.
HashMaps vs TreeMaps
TreeMaps are considerably similar to HashMaps. There are two main differences between these two classes.
- HashMaps are implemented as a Hash Table. TreeMaps are implemented based on Red-Black Tree Structure
If you are not aware of Hash Tables and Red-Black Tree Structure, please refer to the linked articles to get a better idea. I will be talking about Hash Tables later in this article series as well.
- HashMap does not maintain order. TreeMaps are ordered by the key.
Here is a small code snippet that explains the difference between HashMaps and TreeMaps.
//Creating a TreeMap
TreeMap<Integer, String> myTreeMap = new TreeMap<>();
myTreeMap.put(34, "Smith");
myTreeMap.put(62, "Virat");
myTreeMap.put(1, "Marnus");
myTreeMap.put(8, "Stokes");
myTreeMap.put(2, "Williamson");
System.out.println("TreeMap : " + myTreeMap);
//Creating a HashMap
HashMap<Integer, String> myHashMap = new HashMap<>();
myHashMap.put(39, "Smith");
myHashMap.put(61, "Virat");
myHashMap.put(9, "Marnus");
myHashMap.put(13, "Stokes");
myHashMap.put(4, "Williamson");
System.out.println("HashMap : " + myHashMap);
TreeMap : {1=Marnus, 2=Williamson, 8=Stokes, 34=Smith, 62=Virat}
HashMap : {4=Williamson, 39=Smith, 9=Marnus, 61=Virat, 13=Stokes}
Similarities
- Both are unsynchronized and should be synchronized explicitly to be used in a thread-safe environment
- Only contains unique elements. (Key should be unique)
- Keys can’t be null. Values can be null.
//Creating a TreeMap
TreeMap<Integer, String> myTreeMap = new TreeMap<>();
myTreeMap.put(34, "Smith");
myTreeMap.put(62, "Virat");
myTreeMap.put(null, "Bro"); // Causes NullPointerException
myTreeMap.put(4, null); //This is fine
System.out.println("TreeMap : " + myTreeMap);
- Methods are almost the same.
I am not going to list down the methods here. You can take a look at all the available methods here in the Java Documentation
Now you know where to go to when you want to store key/value pairs ordered by the key.
Thank you for reading my article. I hope you learned something valuable from it. If you did, drop a like and follow my blog to get notifications when I publish new articles. I write articles about coding, cricket and things that I find interesting. I try to publish articles every other day. Have a nice day ✌