

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Difference Between HashMap and TreeMap in Java
In this post, we will understand the difference between hashmap and treemap, associated with Java.
HashMap
It is a hash table in Java.
It is based on the implementation of ‘map’ interface.
It implements ‘Map, ‘Cloneable’, and ‘Serializable’ interfaces.
It allows a single null key.
It also allows multiple null values.
It is quicker in comparison to Treemap.
This is because it provides constant-time performances, i.e O(1) for operations like ‘get’ and ‘put’.
It doesn’t perform sorting on keys.
Hence it allows heterogeneous elements in the HashMap.
It doesn’t maintain the order of elements.
It can be used when a key-value pair in a sorted order is NOT needed.
It uses the ‘equals’ method of Object class to compare keys.
The ‘equals’ method of Map class overrides it.
It only contains basic methods like ‘KeySet’, ‘get’, ‘put’.
TreeMap
It is a tree structure used in Java.
It is based on the implementation of ‘map’ interface.
It implements ‘NavigableMap’, ‘Cloneable’, and the ‘Serializable’ interface.
It doesn’t allow null keys.
It allows multiple null values.
It allows homogeneous values as a key since it is sorted.
It is slow in comparison to HashMap since it provides complexity of O(log(n)) for most of the operations such as add(), remove() and contains().
It uses a Red-Black tree internally.
Red black tree is a self-balancing Binary Search Tree.
The compareTo() method is used in order to compare keys.
It has many functionalities such as tailMap(), firstKey(), lastKey(), pollFirstEntry(), pollLastEntry().
The elements are sorted in ascending order, also known as natural order.
It is used when the requirement is a key-value pair in a sorted order.
- Related Questions & Answers
- Difference between TreeMap, HashMap, and LinkedHashMap in Java
- Difference between TreeMap, HashMap and LinkedHashMap in Java programming
- Differences between TreeMap, HashMap and LinkedHashMap in Java
- What is the differences between TreeMap, HashMap and LinkedHashMap in Java?
- Difference between HashMap and ConcurrentHashMap in Java
- Difference between HashTable and HashMap in Java
- Difference between HashMap and HashTable in Java.
- Difference between EnumMap and HashMap in Java
- Difference between HashMap and HashSet in Java.
- Difference Between HashMap and LinkedHashMap in Java
- Difference between HashMap and ConcurrentHashMap
- Java Program to convert HashMap to TreeMap
- Program to convert HashMap to TreeMap in Java
- Difference between Concurrent hash map and Synchronized hashmap in Java
- How to implement HashMap, LinkedHashMap, and TreeMap in JShell in Java 9?