Java TreeMap Collection

Java TreeMap collection is a Red-Black tree-based implementation.

The Treemap class extends the AbstractMap class and implements the NavigableMap interface, which internally implements the SortedMap interface.

The map by default is sorting based on keys. The sorting totally depends on the constructor we used to create the TreeMap.

A tree map is not thread safe as it is not synchronised and can be accessed by multiple threads.

A tree map can have multiple null values, and no null key is allowed. Adding a null key will throw a NullPointerException.

TreeMap Hierarchy:

TreeMap Example:

Note: I always try to make things easy and simple, please read comments while reading code snippet will help to understand better.

Note: In the above example, the map key value got pushed randomly and while fetching the same gives us natural sorted map depending on the keys.

TreeMap Methods:

put(key, value) → Adding an element to the TreeMap using key value pair.

replace(key, replaceValue) → Method having two parameters replace value and return the updated replaced value.

replace(key, originalValue, replaceValue) → this method with three parameters use to replace value and return true if got replaced by same key and old value passed in method parameter.

size() → method will return total number of key value pairs

firstKey() → method will return first key of sorted TreeMap.

lastKey() → method will return last key of sorted TreeMap.

containsKey() → method will return true if specified key is found in TreeMap.

containsValue() → method will return true if specified value is found in TreeMap.

get() → method will return the specified value

Clear() → method will remove all the key value pairs

values() → method will return the collection of value in the TreeMap.

keySet() → method will return the collection of key in the TreeMap.

TreeMap Methods Example:

Note: I always try to make things easy and simple, please read comments while reading code snippet will help to understand better.

OUTPUT:

Some More TreeMap Methods Example:

Note: I always try to make things easy and simple, please read comments while reading code snippet will help to understand better.

OUTPUT:

Imran Khan

Specialist Master (Architect) with a passion for cutting-edge technologies like AEM (Adobe Experience Manager) and a proven track record of delivering high-quality software solutions.

  • Languages: Java, Python
  • Frameworks: J2EE, Spring, Struts 2.0, Hibernate
  • Web Technologies: React, HTML, CSS
  • Analytics: Adobe Analytics
  • Tools & Technologies: IntelliJ, JIRA

🌐 LinkedIn

📝 Blogs

📧 Imran Khan