×

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

Java import packages

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

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.

Tilt operator in Java | Tilde operator in Java Example

The symbol designates it as a unary operator (pronounced as the tilde). It gives back the bit's complement or inverse. Every 0 turns into a 1, and every 1 back...

3 minutes read.

POJO in Java

Plain old Java Object, in short, is called POJO in Java. POJO is an everyday object that is not subject to any specific limitations. We can use POJO in any Java...

3 minutes read.

C# vs Java

Difference Between C# and Java C# and Java both languagesare popularly used programming languages. They both are derived from C/C++ programming and follow Object Oriented Programming approach. Even so, both these...

4 minutes read.

Java StringWriter Class

The StringWriter class is a character stream in which it is used to store the output consisting of characters into the string buffer. Upon collecting output into a string buffer,...

3 minutes read.

Root exception in java

Java: The main feature of java which is not in C or object oriented programming language is platform independence. Not only the platform independence there are many other features in java...

3 minutes read.

FizzBuzz Program in Java

FizzBuzz is a well-known children's game. This game helps children learn division. The FizzBuzz game is becoming a popular programming question, appearing frequently in Core Java interviews. This section will...

3 minutes read.

Stone Game in Java

In this tutorial, we will learn to design a stone game in Java. First of all, we will understand what is this game all about. We will grasp it through...

9 minutes read.

How to Create an API in Java?

Introduction The API can be abbreviated as Application Programming Interface. An API is a combination of set of classes and interfaces. It is also equivalent to a simple java program. To...

12 minutes read.

Minimum Difference Between Groups of Size Two in Java

There is given an array with various integers in it. The goal is to divide the elements into distinct groups, each of which has just two, so that the difference...

3 minutes read.

Creating a Custom Generic Class in Java

To indicate parameter types when creating generic classes, we utilize the <> symbol. The syntax used to generate objects of a generic class is as follows. // To create an instance...

4 minutes read.

&amp;&amp; Operator in Java

“ && ” is the conditional - And operator in Java. In Java, it is an example of a logical operator. In Java, the “ & ” operator has two...

3 minutes read.

Java Primitive Data Types

Primitive data types are the simplest data types in a programming language. They’re predefined in the language. The names of the primitive types are quite descriptive of the values that...

2 minutes read.

Java Console

If there is a character-based console device connected to the active Java virtual machine, it can be accessed using methods provided by the Java.io.Console class. JDK 6 adds the Console...

3 minutes read.

Concurrent Modification Exception In Java

When an object is attempted to be updated concurrently when it is not allowed, the ConcurrentModificationException arises. This error typically occurs while using Java Collection classes. When another thread is iterating...

5 minutes read.

Java Import Keyword

Java's import keyword used in the code that follows the import statement, a Java class is declared. Once a Java class is declared, it is possible to use the class...

6 minutes read.

Java Math.multiplyExact() method in Java

Java has an inbuilt math function called Math.multiplyExact() that returns the sum of the parameters. If the result exceeds an integer, an exception is thrown. There is no need to...

2 minutes read.

What’s new in Java 12

On March 19th, 2019, the Java 12th edition was released. After releasing this edition, they have decided to release every new edition every six months. This version is the advanced...

5 minutes read.

Java Obfuscator

Obfuscation is the process of making something unclear or difficult to interpret. Obfuscators are being used in programming to protect the source code from hackers. In this article, we will...

8 minutes read.