Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet HTML/CSS Java JavaScript Node.js Python Python 3.11, Pandas, SQL
      Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. Java
  4. Complete Guide to TreeMap in Java with Examples

Complete Guide to TreeMap in Java with Examples

Date- Jul 21,2023 Updated Mar 2026 4048
java treemap

Overview of TreeMap

The TreeMap class is part of the Java Collections Framework and implements the SortedMap interface. It maintains its elements in a sorted order based on the natural ordering of keys or a specified comparator. This makes TreeMap ideal for scenarios where you need a sorted collection of key-value pairs, such as managing a leaderboard in a game or maintaining a sorted list of contacts.

One of the key advantages of using a TreeMap is its ability to perform operations like searching, inserting, and deleting elements in logarithmic time complexity. This efficiency is achieved through the underlying Red-Black tree structure, which ensures that the elements are always balanced and sorted.

TreeMap is particularly useful in real-world applications where you need to process data in a sorted manner. For instance, it can be used in applications like databases, where records need to be sorted based on some key, or in web applications that require sorting of user-generated content.

Prerequisites

To effectively use TreeMap in Java, you should have a basic understanding of Java programming, including familiarity with classes, objects, and the Java Collections Framework. Additionally, knowledge of how comparators work will be beneficial when you need to implement custom sorting logic.

Usage of TreeMap

To use a TreeMap, you need to import the java.util.TreeMap class:

import java.util.TreeMap;

You can create a new instance of TreeMap using its default constructor or by providing a custom comparator if needed:

// Default constructor - sorts elements based on natural ordering of keys
TreeMap<Integer, String> treeMap = new TreeMap<>();

// Using a custom comparator for sorting elements
TreeMap<String, Integer> customTreeMap = new TreeMap<>((a, b) -> b.compareTo(a));

Adding and Accessing Elements

You can add elements to the TreeMap using the put() method, and retrieve elements using the get() method:

treeMap.put(1, "One");
treeMap.put(2, "Two");
treeMap.put(3, "Three");

String value = treeMap.get(2); // Returns "Two"
System.out.println("Value at 2 = " + value);

In this example, we added three key-value pairs to the TreeMap and retrieved the value associated with the key '2'. This demonstrates the simplicity of adding and accessing elements in a TreeMap.

Iterating through TreeMap

You can iterate through the elements of a TreeMap using various methods, such as keySet(), entrySet(), or values():

// Using keySet()
for (Integer key : treeMap.keySet()) {
    String value1 = treeMap.get(key);
    System.out.println(key + " = " + value1);
}

// Using entrySet()
for (Map.Entry<Integer, String> entry : treeMap.entrySet()) {
    System.out.println(entry.getKey() + " -> " + entry.getValue());
}

// Using values()
for (String value1 : treeMap.values()) {
    System.out.println(value1);
}

Each of these methods provides a different way to access the elements in a TreeMap, allowing you to choose the method that best suits your needs.

Other Useful Methods

The TreeMap class provides many useful methods, including:

  • size() - returns the number of key-value pairs in the map.
  • containsKey() - checks if a specific key exists in the map.
  • containsValue() - checks if a specific value exists in the map.
  • remove() - removes the key-value pair associated with a specific key.
  • firstKey() - retrieves the first (lowest) key in the map.
  • lastKey() - retrieves the last (highest) key in the map.

Make sure to check the Java documentation for a complete list of available methods and their functionality.

Edge Cases & Gotchas

When using TreeMap, there are a few edge cases and gotchas to be aware of:

  • Null Keys: A TreeMap does not allow null keys. Attempting to add a null key will result in a NullPointerException.
  • Non-Comparable Keys: If you use a custom comparator, ensure that all keys are comparable with each other. If not, you may encounter a ClassCastException.
  • Thread Safety: TreeMap is not synchronized. If you need to use it in a multi-threaded environment, consider using Collections.synchronizedMap() or using ConcurrentSkipListMap.

Performance & Best Practices

TreeMap operations such as insertion, deletion, and lookup are generally O(log n) due to its underlying Red-Black tree structure. Here are some best practices to keep in mind:

  • Choose the Right Comparator: When you create a TreeMap with a custom comparator, ensure that it is consistent with the equals method. This helps prevent unexpected behavior.
  • Avoid Null Values: Ensure that you do not insert null keys or values, as this will lead to exceptions.
  • Use Appropriate Data Types: Use the most efficient data types for your keys to minimize memory usage and improve performance.

Conclusion

In this article, we covered the basics of using TreeMap in Java. It's a powerful data structure that allows you to store and access elements in sorted order based on keys. Remember to explore the Java documentation for a deeper understanding of the available methods and functionalities of the TreeMap class.

  • TreeMap implements the SortedMap interface, maintaining elements in sorted order.
  • It provides efficient operations for adding, retrieving, and removing elements.
  • Be cautious of null keys and ensure keys are comparable when using custom comparators.
  • Utilize the various iteration methods to effectively access elements.
Complete Guide to TreeMap in Java with Examples

S
Shubham Batra
Programming author at Code2Night โ€” sharing tutorials on ASP.NET, C#, and more.
View all posts โ†’

Related Articles

Complete Guide to Hashmap in Java with Examples and Best Practices
Jul 20, 2023
Complete Guide to HashSet in Java with Examples and Best Practices
Jul 18, 2023
Complete Guide to Using Vectors in Java with Examples
Jul 16, 2023
Complete Guide to TreeSet in Java with Examples and Explanations
Jul 19, 2023
Previous in Java
LinkedHashMap in Java
Next in Java
Mastering Java Arrays: A Complete Guide with Examples
Buy me a pizza

Comments

On this page

๐ŸŽฏ

Interview Prep

Ace your Java interview with curated Q&As for all levels.

View Java Interview Q&As

More in Java

  • User-defined data types in java 6252 views
  • Master Java Type Casting: A Complete Guide with Examples 6229 views
  • How to add (import) java.util.List; in eclipse 5810 views
  • org.openqa.selenium.SessionNotCreatedException: session not … 5764 views
  • java.lang.IllegalStateException: The driver executable does … 5095 views
View all Java posts โ†’

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1770
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • HTML/CSS
  • Java
  • JavaScript
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ยท  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor