Skip to content
Related Articles

Related Articles

Similarities Between TreeMap and TreeSet in Java
  • Last Updated : 28 Jan, 2021
GeeksforGeeks - Summer Carnival Banner

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

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

Similarities between TreeSet and TreeMap in java.

  1. Both TreeMap and TreeSet belong to java.util package.
  2. Both are the part of the Java Collection Framework.
  3. They do not allow null values.
  4. Both are sorted. Sorted order can be natural sorted order defined by Comparable interface or custom sorted order defined by Comparator interface.
  5. They are not synchronized by which they are not used in concurrent applications.
  6. Both Provide O(log(n)) time complexity for any operation like put, get, containsKey, remove.
  7. Both TreeSet and TreeMap Internally uses Red-Black Tree.

Illustration of TreeMap and TreeSet:

Java




// Java program to demonstrate some basic functions
// of TreeMap and TreeSet
  
import java.util.*;
import java.io.*;
  
class GFG {
    public static void main (String[] args) {
          
      TreeSet<Integer> st=new TreeSet<>();
      st.add(4);
      st.add(5);
      st.add(6);
      st.add(8);
      st.add(4);
        
        
      TreeMap<Integer,Integer> tm=new TreeMap<>();
      tm.put(2,5);
      tm.put(3,6);
      tm.put(4,6);
      tm.put(2,3);
        
      System.out.println(st);
      System.out.println(tm);
        
        
        
    }
}
Output
[4, 5, 6, 8]
{2=3, 3=6, 4=6}

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :