CoderSathi
  • Tutorial
    • Java Tutorial
    • Swing Tutorial
    • JDBC Tutorial
    • Java String Tutorial
    • Servlet and JSP Tutorial
  • Mongo DB
  • AWS
  • DevOps
  • Linux
  • Git
Home > Java > TreeMap in Java

Java Tutorial

  • Introduction
    • What is Java
    • History Of Java
    • Install Java
    • What is JVM
    • JDK vs JRE vs JVM
    • Java Bytecode
    • OOP vs POP
    • Compile and Run Java
  • Tokens, Expressions and Control Structures
    • Primitive data types
    • Integers
    • Floating Points
    • Characters
    • Booleans
    • User Defined Data Type
    • Declarations
    • Constants
    • Identifiers
    • Literals
    • Type Conversion and Casting
    • Variables
    • Default Variable Initialization
    • Command Line Arguments
    • Arrays of Primitive Types
    • Comment Syntax
    • Garbage Collection
    • Expressions
    • Operators
    • Arithmetic Operator
    • Bitwise and Shift Operator
    • Comparison or Relational Operators
    • Logical Operators
    • Assignment Operators
    • Ternary Operator
    • Increment and Decrement Operator
    • Control Statements
  • OOP Concepts
    • Class and Object
    • Create Class Instance
    • Method
    • Abstraction
    • Encapsulation
    • this keyword
    • Constructor
    • Pass by Value
    • Access Modifier/Control
    • Polymorphism
    • Method Overloading vs Method Overriding
    • Recursion
    • Nested and Inner Class
  • Inheritance and Packaging
    • Inheritance
    • extends Keyword
    • super Keyword
    • Object Class
    • Abstract class
    • Final Class
    • Java Package
    • Interface
  • Handling Error/ Exceptions
    • What is Exception
    • Exception Handling Keywords
    • Common Java Errors
    • User Defined Exception
    • Throwing and re-throwing Exception
    • finally Block
  • Strings
    • Java String Tutorial
  • Threads
    • Introduction
    • Create Thread
    • Thread Lifecycle
    • Thread Priority
    • Thread Synchronization
    • Inner Thread Communication
    • Thread Deadlock
  • IO and Streams
    • java.io Package
    • Files and Directories
    • Byte Stream
    • Character Stream
    • Console Input and Output
    • Serializable and Deserializable
  • Core Packages
    • java.lang Package
    • Math
    • Wrapper Classes
    • java.lang.Number
    • Double
    • Float
    • Integers
    • java.lang.Byte
    • java.lang.Short
    • java.lang.Long
    • java.lang.Character
    • java.lang.Boolean
    • java.util package
    • Vector Class
    • Stack Class
    • Dictionary Class
    • Hashtable
    • Enumeration or Enum
    • Generate Random Number
  • Holding Collection of Data
    • Arrays
    • Map
    • List
    • Set
    • Collection Interface
    • Collections Class
    • ArrayList
    • HashSet
    • TreeSet
    • Comparator
  • Java Bean
    • What is Java Bean
    • Advantages and Disadvantages of Java Bean
    • Java Beans API
    • Introspection
    • Java Bean Properties
    • Bound and Constrained Properties
    • BeanInfo Interface
    • Customizers
    • Java Beans Persistence
    • BeanDescriptor

TreeMap in Java

Learn the concepts, implementation details, and practical steps with a clean developer-focused walkthrough.

Yuba Raj Kalathoki
By Yuba Raj Kalathoki
Last updated: July 1, 2026 · 3 min read · 0 Comments
Share: in X

TreeMap is a widely used data structure in the Java programming language. It is a part of the Java Collection Framework and is an implementation of the SortedMap and NavigableMap interfaces. It provides a way to store and retrieve data in sorted order, based on the keys. In this blog post, we will discuss what TreeMap is, how it works, and how to use it in Java, including examples of all the available methods.

What is TreeMap in Java?

A TreeMap is a collection that stores key-value pairs, where each key is unique and is associated with a specific value. Unlike HashMap, it stores the elements in sorted order, based on the keys. It is implemented using a red-black tree, which is a self-balancing binary search tree. This tree structure allows for fast and efficient data retrieval, insertion, and deletion.

Why use TreeMap in Java?

TreeMap is useful in situations where we need to store data in sorted order, based on the keys. It is particularly useful in situations where we need to perform operations such as searching, traversing, and range searching, based on the keys.

TreeMap is also useful in situations where we need to maintain the natural ordering of elements, or need to sort elements based on custom comparators. It is a good alternative for HashMap when we need to maintain the order of elements.

How to use TreeMap in Java?

Using a TreeMap in Java is relatively simple. To create a TreeMap, we first need to import the java.util package, which contains the TreeMap class.

Create and add data in TreeMap

The example of creating a TreeMap and adding data to it is given below:

import java.util.TreeMap;

TreeMap<Integer, String> map = new TreeMap<Integer, String>();
map.put(1, "one");
map.put(3, "three");
map.put(2, "two");

The output of the above example code is:

{1=one, 2=two, 3=three}

Once we have created the TreeMap, we can add data to it using the put() method. The put() method takes two arguments: the first parameter is the key and the second one is the value. In the example above, we are adding three key-value pairs to the TreeMap. As we can see in the output above, the elements are stored in a sorted order based on the keys.

Get data from TreeMap

We can also retrieve data from a TreeMap using the get() method. For example, to retrieve the value associated with the key 2, we can use the following code:

String value = map.get(2);

The output of this code will be:

two

This is because the get method accepts the key as a parameter. Hence, the key is 2 in the map object and it has assigned a value two.

There are many methods available in TreeMap. Some of them are given below:

MethodDescription
K firstKey()Returns the first (lowest) key currently in this map.
K lastKey()Returns the last (highest) key currently in this map.
K ceilingKey(K key)Returns the least key greater than or equal to the given key, or null if there is no such key.
K floorKey(K key)Returns the greatest key less than or equal to the given key, or null if there is no such key.
K higherKey(K key)Returns the least key strictly greater than the given key, or null if there is no such key.
K lowerKey(K key)Returns the greatest key strictly less than the given key, or null if there is no such key.

In addition to these methods, TreeMap also provides other useful methods such as remove(), clear(), and size() that work similarly to HashMap.

To know more detail about TreeMap you can visit to the official documentation by clicking here.

Related Posts:

  • Control Statements in Java
  • Dictionary Class in Java
  • MySQL Commands for Developers
  • Map in Java
  • Packages in Java: A Guide to Modular, Maintainable Code
  • List in Java
Tags:java
Was this article helpful?
← Previous ArticleHashMap in java
Next Article →LinkedHashMap in Java

Recent Posts

  • How to implement Passwordless Authentication in Spring Boot: A Step-by-Step Guide
  • How to Use AWS CloudFront Signed URLs in Spring Boot?
  • How to Fix SSH Agent Forwarding on macOS: The Ultimate Guide for Developers
  • How to Read AWS Secrets Manager in Spring Boot (Step-by-Step)
  • How to Fix “Public Key Retrieval is not allowed” MySQL JDBC Error
CoderSathi

Your go-to resource for Java, Spring Boot, Microservices, AWS, and modern development tutorials.

Linkedin

Quick Links

  • About
  • Contact

Popular Topics

  • Java
  • Spring Boot
  • AWS
  • DevOps
  • MongoDB
  • Linux
  • Git
  • How to
© 2026 CoderSathi. All rights reserved. Privacy Policy · Sitemap