×

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

Can Abstract Classes have Static Methods in Java

Abstract Class An abstract class in Java is one that explicitly uses the keyword "abstract" in its declaration. There are options for both non-abstract and abstract techniques (method with the body)....

4 minutes read.

Swastika Pattern in Java

This part teaches us how to create the Swastika Pattern in Java utilizing user-defined columns and rows as well as stars or other special characters.A Java pattern application that is...

2 minutes read.

Manachers Algorithm in Java

Here, we'll go over the four scenarios once more in an effort to approach them differently and use the same strategy. The values of (centerRightPosition - currentRightPosition) and LPS length at...

3 minutes read.

Median Of Stream Of Running Integers in Java

An integer array is given to us. Compute the median of the elements traversed so far in the input array. For the sake of simplicity, assume that there are no...

10 minutes read.

What is interpreter in Java?

The programming language Java is platform-neutral. Therefore, can use Java on any platform that supports the Java processor. The Piece of software transforms the Java bytecode contained in the class...

5 minutes read.

nth Prime Number in Java

A number is considered prime if only divisible by one and itself. Prime numbers include, for example, 2, 3, 5, 7, 11, etc. In looking at it another way, a...

5 minutes read.

Mutable class in Java

A language for object-oriented programming is Java. Because this is an object-oriented language of programming, all of its mechanisms and methods are based on objects. Java has a concept of...

6 minutes read.

HashMap Vs HashTable

HashMap HashMap is the basic implementation of the map interface in Java. HashMap stores the data in key and value pairs. Keys are used to access the value of the element. It...

5 minutes read.

How to declare string array in Java

Introduction Array is a data structure with a fixed size, which allows us to store elements of similar type. Data of primitive types like int, char, float, string, etc. can be...

2 minutes read.

Date time API in java

Introduction: In this text, we can talk approximately Data time API in java. The java.time, java.util, java.sql, and java.text packages contain classes that represent dates and times. The following classes are...

4 minutes read.

Java Boolean toValue() Method

The valueOf() method of Java Boolean class returns a Boolean object representing the given Boolean or String value. It returns true, if the specified Boolean or string object is true...

2 minutes read.

Program to find the duplicate characters in a string

Problem statement You have given with a string and your task is to find out the repeated characters from the string and print them. If no character is repeated, then you...

2 minutes read.

Difference between Constructor and Method in Java

What is Constructor? In Constructor, we will discuss constructors and also will discuss default constructors and finally, we will discuss overloading constructors. A constructor is a method that is used to...

13 minutes read.

Association in Java

In Java, association refers to the link between two classes established by their objects. One-to-one, one-to-many, and many-to-many connections are managed via association. The Association defines the multiplicity between objects...

5 minutes read.

Java Integer shortValue() method

The shortValue() method of Java Integer class returns a short value for this Integer after a narrowing primitive conversion. Syntax public short shortValue () Parameters NA Overrrides: The shortValue () overrides : shortValue in class Number  Return Value This...

1 minute read.

Minimum XOR value pair in Java

In this section, you will discuss about minimum XOR value pair in Java. The objective is to enforce a value that indicates the least XOR values of the two numbers from...

4 minutes read.

The final Keyword in Java

The final keyword is employed in several instances. Firstly, the non-access modifier final only applies to variables, methods, and classes. The final can be used in the following situations. Final Variables When...

6 minutes read.

Thread Concept in Java

What is a Thread? A subprocess that is lightweight in Java is known as a thread. It is the smallest unit of a process. For the running of multiple tasks parallelly...

3 minutes read.

Java Output Formatting

Sometimes we want a program's output to be displayed in a specific format. The printf () function in the C programming language can be used to achieve this. We will...

4 minutes read.

Java LinkedList

LinkedList Java The Java LinkedList is used to store the elements by using a doubly linked list. It contains the duplicate items, also maintains the order of the insertion, the class...

5 minutes read.