Friday, October 10, 2025
HomeLanguagesJavaDifference between TreeMap and TreeSet in Java

Difference between TreeMap and TreeSet in Java

TreeSet is mainly an implementation of SortedSet in java where duplication is not allowed and objects are stored in sorted and ascending order.

Some important features of the TreeSet are:

  • In TreeSet duplicate values are not allowed because it implements the SortedSet interface.
  • Objects in a TreeSet are stored in ascending order.
  • In TreeSet the insertion order of elements does not maintain.

TreeMap is an implementation of Map Interface. TreeMap is also an implementation of NavigableMap along with AbstractMap class.

Some important features of the TreeMap are:

  • In TreeMap null keys(like Map) are not allowed and thus a NullPointerException is thrown (Multiple null values may be associated with different keys).
  • TreeMap does not support the Entry.setValue method.

Below is the illustration of TreeSet and TreeMap in Java:

Example 1:

Java




// Illustration of TreeMap and TreeSet in Java
import java.io.*;
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
        TreeSet<Integer> set = new TreeSet<>();
        set.add(3);
        set.add(4);
        set.add(3);
        set.add(5);
  
        TreeMap<Integer, Integer> tm = new TreeMap<>();
        tm.put(2, 4);
        tm.put(3, 5);
        tm.put(4, 5);
        tm.put(2, 3);
        System.out.println(set);
        System.out.println(tm);
    }
}


Output

[3, 4, 5]
{2=3, 3=5, 4=5}

Example 2:

Java




// Illustration of TreeMap and TreeSet in Java
import java.io.*;
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
        TreeSet<String> l = new TreeSet<>();
        l.add("geeks");
        l.add("FOR");
        l.add("geeks");
        l.add("tutorial");
  
        TreeMap<Integer, String> l1 = new TreeMap<>();
  
        l1.put(1, "geeks");
        l1.put(2, "FOR");
        l1.put(3, "geeks");
        l1.put(4, "tutorial");
        System.out.println(l);
        System.out.println(l1);
    }
}


Output

[FOR, geeks, tutorial]
{1=geeks, 2=FOR, 3=geeks, 4=tutorial}
S. No.

TreeSet

TreeMap

1. TreeSet implements SortedSet in Java. TreeMap implements Map Interface in Java
2. TreeSet stored a single object in java. TreeMap stores two Object one Key and one value.
3. TreeSet does not allow duplication Object in java. TreeMap in java allows duplication of values.
4. TreeSet implements NavigableSet in Java. TreeMap implements NavigableMap in Java.
5. TreeSet is sorted based on objects. TreeMap is sorted based on keys.
RELATED ARTICLES

Most Popular

Dominic
32348 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6715 POSTS0 COMMENTS
Nicole Veronica
11878 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11941 POSTS0 COMMENTS
Shaida Kate Naidoo
6837 POSTS0 COMMENTS
Ted Musemwa
7096 POSTS0 COMMENTS
Thapelo Manthata
6791 POSTS0 COMMENTS
Umr Jansen
6791 POSTS0 COMMENTS