×

Java TreeMap

TreeMap in Java with Example

Java TreeMap implements the NavigableMap interface. It extends Map Interface. Java TreeMap is based on the red-black Tree implementation. It stores the key-value pair in sorted order. The values based on the key. It contains unique elements, i.e. it does not contain the duplicate values. It does not provide null keys but contains multiple null values. It maintains the ascending order. If you assign a null key, then it throws NullPointerException. It is not synchronized, so it is not thread-safe. Time Complexity of TreeMap: TreeMap based on Red-Black Tree data structure. The complexity of the TreeMap is O(log n) time. The constructor of TreeMap:
  1. TreeMap (): It is used to construct the empty TreeMap which is natural sorted.
  2. TreeMap (Map m): It is used to initialize the treemap with the entries of map m which is natural sorted.
  3. TreeMap (Comparator c): It is used to construct the empty tree-based map which sorted by using Comparator.
  4. TreeMap (SortedMap s): It is used to initializes the treemap with entries from s, which sorted as SortedMaps.

Methods of TreeMap:

  1. containsKey (Object key): it returns true if the specified key is present in the TreeMap.
Example:
import java.util.*;
public class TreeMapDemo {
public static void main (String [] args) {
 TreeMap<Integer, String> l = new TreeMap<Integer, String> ();
l.put (10, "Java");
l.put (15, "HTML");
l.put (20, "Python");
l.put (25, "JavaScript");
l.put (30, "C++");
System.out.println ("Initial Mappings are: " + l);
System.out.println ("Is the key '10' present?" + l.containsKey (10));
System.out.println ("Is the key '55' present?" + l.containsKey (55));
} }
Output:
Initial Mappings are: {10=Java, 15=HTML, 20=Python, 25=JavaScript, 30=C++}
Is the key '10' present? true
Is the key '55' present? false
  1. containsValue (Object value): It returns true if the specified value is present in the TreeMap.
Example:
import java.util.*;
public class TreeMapDemo {
public static void main (String [] args) {
 TreeMap<Integer, String> l = new TreeMap<Integer, String> ();
l.put (10, "Java");
l.put (15, "HTML");
l.put (20, "Python");
l.put (25, "JavaScript");
l.put (30, "C++");
System.out.println ("Initial Mappings are: " + l);
System.out.println ("Is the value 'Java' present?" + l.containsValue ("Java"));
System.out.println ("Is the value 'Python' present?" + l.containsValue ("Python"));
} }
Output:
Initial Mappings are: {10=Java, 15=HTML, 20=Python, 25=JavaScript, 30=C++}
Is the value 'Java' present? true
Is the value 'Python' present? true
  1. get (Object Key): It is used to get the value of a particular key from the map.
Example:
import java.util.*;
public class TreeMapDemo {
public static void main (String [] args) {
 TreeMap<Integer, String> l = new TreeMap<Integer, String> ();
l.put (10, "Java");
l.put (15, "HTML");
l.put (20, "Python");
l.put (25, "JavaScript");
l.put (30, "C++");
System.out.println ("Initial Mappings are: " + l);
System.out.println ("The value is: " + l.get (20));
System.out.println ("The value is: " + l.get (25));
} }
Output:
Initial Mappings are: {10=Java, 15=HTML, 20=Python, 25=JavaScript, 30=C++}
The value is: Python
The value is: JavaScript
  1. put (object K, object V): It is used to insert the value of the specified key in the Map.
Example:
import java.util.*;
public class TreeMapDemo {
public static void main (String [] args) {
 TreeMap<Integer, String> l = new TreeMap<Integer, String> ();
l.put (10, "Java");
l.put (15, "HTML");
l.put (20, "Python");
l.put (25, "JavaScript");
l.put (30, "C++");
System.out.println ("Initial Mappings are: " + l);
String return= (String) l.put (20, "All");
System.out.println ("Returned value is: " + return);
System.out.println ("New map is: " + l);
} }
Output:
Initial Mappings are: {10=Java, 15=HTML, 20=Python, 25=JavaScript, 30=C++}
Returned value is: Python
New map is: {10=Java, 15=HTML, 20=All, 25=JavaScript, 30=C++}
  1. clear (): It is used to remove all mapping from the TreeMap.
Example:
import java.util.*;
public class TreeMapDemo {
public static void main (String [] args) {
 TreeMap<Integer, String> l = new TreeMap<Integer, String>();
l.put (10, "Java");
l.put (15, "HTML");
l.put (20, "Python");
l.put (25, "JavaScript");
l.put (30, "C++");
System.out.println ("Initial Mappings are: " + l);
l.clear ();
System.out.println ("After clearing the map: "+ l);
} }
Output:
Initial Mappings are: {10=Java, 15=HTML, 20=Python, 25=JavaScript, 30=C++}
After clearing the map: {}
  1. clone (): This is used to return the same copy of the TreeMap.
Example:
import java.util.*;
public class TreeMapDemo {
public static void main (String [] args) {
 TreeMap<Integer, String> l = new TreeMap<Integer, String> ();
l.put (10, "Java");
l.put (15, "HTML");
l.put (20, "Python");
l.put (25, "JavaScript");
l.put (30, "C++");
System.out.println ("Initial Mappings are: " + l);
System.out.println ("The cloned map look like this: " + l.clone ());
} }
Output:
Initial Mappings are: {10=Java, 15=HTML, 20=Python, 25=JavaScript, 30=C++}
The cloned map look like this: {10=Java, 15=HTML, 20=Python, 25=JavaScript, 30=C++}
  1. size (): This method is used to return the size of the TreeMap.
Example:
import java.util.*;
public class TreeMapDemo {
public static void main (String [] args) {
 TreeMap<Integer, String> l = new TreeMap<Integer, String>();
l.put (10, "Java");
l.put (15, "HTML");
l.put (20, "Python");
l.put (25, "JavaScript");
l.put (30, "C++");
System.out.println ("Initial Mappings are: " + l);
System.out.println ("The map size is: " + l.size ());
} }
Output:
Initial Mappings are: {10=Java, 15=HTML, 20=Python, 25=JavaScript, 30=C++}
The map size is: 5
  1. putAll (Map m): This is used to copy all elements from the map to another map.
Example:
import java.util.*;
public class TreeMapDemo {
public static void main (String [] args) {
 TreeMap<Integer, String> l = new TreeMap<Integer, String>();
l.put (10, "Java");
l.put (15, "HTML");
l.put (20, "Python");
l.put (25, "JavaScript");
l.put (30, "C++");
System.out.println ("Initial Mappings are: " + l);
TreeMap<Integer, String> t = new TreeMap<Integer, String>();
t.putAll (l);
 System.out.println ("The new map: " + t);
} }
Output:
Initial Mappings are: {10=Java, 15=HTML, 20=Python, 25=JavaScript, 30=C++}
The new map: {10=Java, 15=HTML, 20=Python, 25=JavaScript, 30=C++}
  1. keySet (): It returns the set view of keys in the TreeMap.
Example:
import java.util.*;
public class TreeMapDemo {
public static void main (String [] args) {
 TreeMap<Integer, String> l = new TreeMap<Integer, String> ();
l.put (10, "Java");
l.put (15, "HTML");
l.put (20, "Python");
l.put (25, "JavaScript");
l.put (30, "C++");
System.out.println ("Initial Mappings are: " + l);
System.out.println ("The key in the map: " + l.keySet ());
} }
Output:
Initial Mappings are: {10=Java, 15=HTML, 20=Python, 25=JavaScript, 30=C++}
The key in the map: [10, 15, 20, 25, 30]
  1. Values (): This returns the collections view of values in the TreeMap.
Example:
import java.util.*;
public class TreeMapDemo {
public static void main (String [] args) {
 TreeMap<Integer, String> l = new TreeMap<Integer, String> ();
l.put (10, "Java");
l.put (15, "HTML");
l.put (20, "Python");
l.put (25, "JavaScript");
l.put (30, "C++");
System.out.println ("Initial Mappings are: " + l);
System.out.println ("The value in the map: " + l.values ());
} }
Output:
Initial Mappings are: {10=Java, 15=HTML, 20=Python, 25=JavaScript, 30=C++}
The value in the map: [Java, HTML, Python, JavaScript, C++]
  1. entrySet (): This returns the Set view of the whole mapping in the map.
Example:
import java.util.*;
public class TreeMapDemo {
public static void main (String [] args) {
 TreeMap<Integer, String> l = new TreeMap<Integer, String> ();
l.put (10, "Java");
l.put (15, "HTML");
l.put (20, "Python");
l.put (25, "JavaScript");
l.put (30, "C++");
System.out.println ("Initial Mappings are: " + l);
System.out.println ("The value in the map: " + l.entrySet ());
} }
Output:
Initial Mappings are: {10=Java, 15=HTML, 20=Python, 25=JavaScript, 30=C++}
The value in the map: [10=Java, 15=HTML, 20=Python, 25=JavaScript, 30=C++]
  1. firstKey (): This returns the first (lowest) key in the sorted TreeMap.
Example:
import java.util.*;
public class TreeMapDemo {
public static void main (String [] args) {
 TreeMap<Integer, String> l = new TreeMap<Integer, String> ();
l.put (10, "Java");
l.put (15, "HTML");
l.put (20, "Python");
l.put (25, "JavaScript");
l.put (30, "C++");
System.out.println ("Initial Mappings are: " + l);
System.out.println ("The lowest key in the map: " + l.firstKey ());
} }
Output:
Initial Mappings are: {10=Java, 15=HTML, 20=Python, 25=JavaScript, 30=C++}
The lowest key in the map: 10
  1. lastKey (): This returns the last (highest) key in the sorted TreeMap.
Example:
import java.util.*;
public class TreeMapDemo {
public static void main (String [] args) {
 TreeMap<Integer, String> l = new TreeMap<Integer, String> ();
l.put (10, "Java");
l.put (15, "HTML");
l.put (20, "Python");
l.put (25, "JavaScript");
l.put (30, "C++");
System.out.println ("Initial Mappings are: " + l);
System.out.println ("The highest key in the map: " + l.lastKey ());
} }
Output:
Initial Mappings are: {10=Java, 15=HTML, 20=Python, 25=JavaScript, 30=C++}

The highest key in the map: 30
  1. remove (Object K): It is used to remove the mapping of the specified key from the TreeMap.
Example:
import java.util.*;
public class TreeMapDemo {
public static void main (String [] args) {
 TreeMap<Integer, String> l = new TreeMap<Integer, String> ();
l.put (10, "Java");
l.put (15, "HTML");
l.put (20, "Python");
l.put (25, "JavaScript");
l.put (30, "C++");
System.out.println ("Initial Mappings are: " + l);
System.out.println ("The value removes in the map: " + l.remove (20));
} }
Output:
Initial Mappings are: {10=Java, 15=HTML, 20=Python, 25=JavaScript, 30=C++}
The value removes in the map: Python
  1. headMap (Object key): This method is used to view the only portion of the map which is less than the parameter key.
Example:
import java.util.*;
public class TreeMapDemo {
public static void main (String [] args) {
 TreeMap<Integer, String> l = new TreeMap<Integer, String>();
l.put (10, "Java");
l.put (15, "HTML");
l.put (20, "Python");
l.put (25, "JavaScript");
l.put (30, "C++");
System.out.println ("Initial Mappings are: " + l);
System.out.println ("The value in the map: " + l.headMap (20));
} }
Output:
Initial Mappings are: {10=Java, 15=HTML, 20=Python, 25=JavaScript, 30=C++}
The value in the map: {10=Java, 15=HTML}
  1. subMap (Object start key, Object endKey): This method is used to view the portion of the map between the ranges of starting point of the key to the end point of key.
Example:
import java.util.*;
public class TreeMapDemo {
public static void main (String [] args) {
 TreeMap<Integer, String> l = new TreeMap<Integer, String> ();
l.put (10, "Java");
l.put (15, "HTML");
l.put (20, "Python");
l.put (25, "JavaScript");
l.put (30, "C++");
System.out.println ("Initial Mappings are: " + l);
System.out.println ("The value in the map: " + l.subMap (15, 30));
} }
Output:
Initial Mappings are: {10=Java, 15=HTML, 20=Python, 25=JavaScript, 30=C++}
The value in the map: {15=HTML, 20=Python, 25=JavaScript}

Related Topics

Method and Block Synchronization in Java

The Synchronization is performed in multi-threading concept. The multi-threading is a concept of parallel running of a program for the execution. In the multi-threading concept, the threads are run by...

3 minutes read.

Java.net.SocketException

Exception The problem occurred during the execution of the program. If an exception occurs in the program, the program gets terminated. To skip the exception occurring statements, we have to handle...

4 minutes read.

Java Math addExact() Method

The addExact() method of Math class returns the sum of the two arguments, throwing an exception if the result overflows a long or an int. Syntax public static int addExact (int x,...

1 minute read.

How to Change the Day in the Date using Java?

To operate with the date and time in Java, we need the Calendar abstract class. It provides a number of helpful interfaces that enable us to convert dates between a...

4 minutes read.

Missing Number in an Arithmetic Progression in Java

Given an array that shows the elements of an orderly arithmetic progression. Find the missing number to complete the succession of elements. Example:  Input: a [ ] = {2 , 4 , 6...

3 minutes read.

Java Network Programming (Socket Programming in Java)

JAVA NETWORK Network programming is used to execute programs across multiple machines that are connected by a network. The java.net package contains a collection of classes and interfaces that provide this...

3 minutes read.

Generics vs Wildcard in Java

In generic programming, the question mark (?) is often referred to as the wildcard. It stands for a mysterious type. The wildcard can be used for many different contexts, such as...

4 minutes read.

Bin Packing Problem Java

Assigning some items with known weights to bins with consistent capacities is necessary for the bin packing problem. The goal is to use the smallest possible boxes while ensuring everything is put...

6 minutes read.

Java Program to Sort an Array of 0's, 1's, and 2’s | Dutch National Flag Problem in Java

The famed Dutch computer programmer Edsger Dijkstra's Dutch Nation Flag (DNF) challenge ranks among the most well-known programming challenges. The Dutch tricolor flag, comprising red, white, and blue, is the...

3 minutes read.

Java program to find frequency of characters in a string

In this article, you will understand the how to find the frequency of characters in strings by using Java programming language. Along with this, you will understand the hashing concept...

3 minutes read.

Abstract Class Program in Java

Abstract Class Program in Java Abstraction is a technique by which a developer hides the implementation details from the user and shows only the functionality.It is not only confined to the...

6 minutes read.

User Defined Exception in Java

An exception is an error (run time error) that happened while a program was being executed. The program stops abruptly whenever the Exception occurs, and the code after the line...

3 minutes read.

How to use scanner in Java

Scanner class in Java is the part of java.util package. Java programming language has various ways to read input from the user, Scanner class is one of the classes to...

5 minutes read.

Thread Safety and How to Achieve it in Java

Before diving into the topic, let’s just recap the concept of Multithreading provided by Java where we can create and execute multiple threads of the same object. When these multiple...

5 minutes read.

Java Integer signum() method

The signum() method of Java Integer class returns the signum function of the specified int value. Syntax public static int signum (int i)  Parameters The parameter ‘i’ represents the value whose signum is to...

1 minute read.

Producer consumer problem in Java using Synchronised block

The producer-consumer problem in Java, commonly known as the bounded-buffer problem, is a well-known multi-process synchronization challenge where we attempt to synchronize many processes. Two processes are involved in the producer-consumer problem:...

3 minutes read.

StringBuilder in Java

StringBuilder in Java Java StringBuilder class is introduced since JDK 1.5. The StringBuilder class is mainly used to create modifiable or mutable strings. Note that the StringBuilder class is not synchronized....

7 minutes read.

Object Oriented Programming (OOPs)

Since the dawn of earth, we have kept on evolving. The need for evaluation comes with the aim of improving the existing systems when something inappropriate is found for the...

5 minutes read.

Static class in Java

In Java, a class is a file containing the Java byte code. It can essentially specifically be executed on the JVM (Java Virtual Machine), fairly significant. The JVM is mostly...

7 minutes read.

Deadlock in Java

Deadlock is when two or more processes wait for the state to do their tasks, but none of them can do so. It is a very common problem that one...

6 minutes read.