Friday, June 12, 2026
HomeLanguagesJavaHow to Create TreeMap in Java?

How to Create TreeMap in Java?

The TreeMap in Java is used to implement Map interface and NavigableMap along with the Abstract Class. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.

To create TreeMap we can use Map class or TreeMap class reference.

Example 1:

Java




// Java program demonstrate how to create a TreeMap
  
import java.util.*;
  
class GFG {
  
    public static void main(String[] args)
    {
        // Declaring a treemap
        TreeMap<Integer, String> map;
  
        // Creating an empty TreeMap
        map = new TreeMap<Integer, String>();
  
        System.out.println("TreeMap successfully"
                           + " created");
    }
}


Output

TreeMap successfully created

Example 2:

Java




// Java program demonstrate how to create and add elements
// to TreeMap
  
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
        // Creating an empty TreeMap using Map interface
        Map<Integer, String> map = new TreeMap<>();
        
        System.out.println("TreeMap successfully"
                           + " created");
  
        // Adding elements
        map.put(1, "Geeks");
        map.put(2, "for");
        map.put(3, "Geeks");
  
        // Printing TreeMap
        System.out.println("TreeMap: " + map);
    }
}


Output

TreeMap successfully created
TreeMap: {1=Geeks, 2=for, 3=Geeks}
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

3 COMMENTS

Most Popular

Dominic
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6897 POSTS0 COMMENTS
Nicole Veronica
12013 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6964 POSTS0 COMMENTS