Java TreeSet

The Java TreeSet class implements the Set interface that uses a tree for storage. The ordering of the elements is maintained by a set using their natural ordering. The TreeSet implements a NavigableSet interface by inheriting AbstractSet class.

There are some key points to remember about TreeSet :

  1. TreeSet class contains unique elements and its access and retrival time quiet fast.
  2. TreeSet class is non synchronized and it doesn't allow null elements.
  3. In TreeSet when trying to insert null as the first value, it was accpeting up to JDK 6, but any insertion of more null values in the TreeSet resulted in NullPointerException. From JDK 7 onwards, null is not at all accepted by TreeSet.
  4. TreeSet serves as an excellent choice for storing large amounts of sorted information which are supposed to be accessed quickly because of its faster access and retrieval time.
  5. The insertion of null values into a TreeSet throws NullPointerException because while insertion of null, it gets compared to the existing elements, and null cannot be compared to any value.

Creating a TreeSet

In order to create a tree set, we must import the java.util.TreeSet package first.


                        Set set = new TreeSet();
                                (or)
                        TreeSet<Integer> numbers = new TreeSet<>();  
                        TreeSet<String> numbers = new TreeSet<>();  
                    
TreeSet constructos

In order to create a HashSet, we need to create an object of the HashSet class. The HashSet class consists of various constructors that allow the possible creation of the HashSet. The following are the constructors available in this class.

Constructor Description Example
TreeSet() It is used to construct an empty tree set that will be sorted in ascending order according to the natural order of the tree set. TreeSet ts = new TreeSet();
TreeSet(Comparator) This constructor is used to build an empty TreeSet object in which elements will need an external specification of the sorting order. TreeSet ts = new TreeSet(Comparator comp);
TreeSet(Collection) his constructor is used to build a TreeSet object containing all the elements from the given collection in which elements will get stored in default natural sorting order. TreeSet t = new TreeSet(Collection col);
TreeSet(SortedSet) This constructor is used to build a TreeSet object containing all the elements from the given sortedset in which elements will get stored in default natural sorting order. TreeSet t = new TreeSet(SortedSet s);
Methods of TreeSet

The TreeSet class provides various methods that allow us to perform various operations on the set.

Method Name Description
add() inserts the specified element to the TreeSet.
addAll() inserts all the elements of the specified collection to the TreeSet.
remove() removes the specified element from the set.
removeAll() removes all the elements from the set.
first() returns the first element of the set.
last() returns the last element of the set.
higher(element) Returns the lowest element among those elements that are greater than the specified element.
lower(element) Returns the greatest element among those elements that are less than the specified element.
ceiling(element) Returns the lowest element among those elements that are greater than the specified element. If the element passed exists in a tree set, it returns the element passed as an argument.
floor(element) Returns the greatest element among those elements that are less than the specified element. If the element passed exists in a tree set, it returns the element passed as an argument.
pollFirst() returns and removes the first element from the set.
headSet(element, booleanValue) The headSet() method returns all the elements of a tree set before the specified element. The booleanValue parameter is optional. Its default value is false. If true is passed as a booleanValue, the method returns all the elements before the specified element including the specified element.
tailSet(element, booleanValue) The tailSet() method returns all the elements of a tree set after the specified element (which is passed as a parameter) including the specified element. The booleanValue parameter is optional. Its default value is true. If false is passed as a booleanValue, the method returns all the elements after the specified element without including the specified element.
subSet(e1, bv1, e2, bv2) The subSet() method returns all the elements between e1 and e2 including e1. The bv1 and bv2 are optional parameters. The default value of bv1 is true, and the default value of bv2 is false. If false is passed as bv1, the method returns all the elements between e1 and e2 without including e1. If true is passed as bv2, the method returns all the elements between e1 and e2, including e1.
retainAll() To perform the intersection between two sets, we use the retainAll() method.
containsAll() To check if a set is a subset of another set or not, we use the containsAll() method.
clone() Creates a copy of the TreeSet.
contains() Searches the TreeSet for the specified element and returns a boolean result.
isEmpty() Checks if the TreeSet is empty.
size() Returns the size of the TreeSet.
clear() Removes all the elements from the TreeSet.
Basic Operations on HashSet

The HashSet class provides various methods to perform different operations on hashset. We will look at some commonly used hashset operations.

  1. ▪ Insert Elements to TreeSet
  2. ▪ Access TreeSet Elements
  3. ▪ Remove Elements
Methods for Navigation: TreeSet class implements NavigableSet, it provides various methods to navigate over the elements of the tree set.
  1. ▪ first() and last() Methods
  2. ▪ ceiling(), floor(), higher() and lower() Methods
  3. ▪ pollfirst() and pollLast() Methods
  4. ▪ headSet(), tailSet() and subSet() Methods
  5. ▪ tailSet(element, booleanValue)
  6. ▪ subSet(e1, bv1, e2, bv2)
Set Operations: The methods of the TreeSet class can also be used to perform various set operations.
  1. ▪ Union of Sets
  2. ▪ Intersection of Sets
  3. ▪ Difference of Sets
  4. ▪ Subset

Insert Elements to TreeSet

add(), addAll() methods is used to insert elements into TreeSet.


                        import java.util.TreeSet;

                        public class InsertElementExample {
                            public static void main(String[] args) {

                                TreeSet<Integer> evenNumbers = new TreeSet<>();

                                // Using the add() method
                                evenNumbers.add(2);
                                evenNumbers.add(4);
                                evenNumbers.add(6);
                                System.out.println("TreeSet: " + evenNumbers);

                                TreeSet<Integer> numbers = new TreeSet<>();
                                numbers.add(1);

                                // Using the addAll() method
                                numbers.addAll(evenNumbers);
                                System.out.println("New TreeSet: " + numbers);
                            }
                        }
                    
Access TreeSet Elements

To access the elements of a tree set, we can use the iterator() method. In order to use this method, we must import java.util.Iterator package.


                        import java.util.TreeSet;
                        import java.util.Iterator;

                        public class AccessElementsExample {
                            public static void main(String[] args) {
                                TreeSet<Integer> numbers = new TreeSet<>();
                                numbers.add(2);
                                numbers.add(5);
                                numbers.add(6);
                                System.out.println("TreeSet: " + numbers);

                                // Calling iterator() method
                                Iterator<Integer> iterate = numbers.iterator();
                                System.out.print("TreeSet using Iterator: ");
                                // Accessing elements
                                while(iterate.hasNext()) {
                                    System.out.print(iterate.next());
                                    System.out.print(", ");
                                }
                            }
                        }
                    
Remove Elements

remove(), removeAll() methods are used to remove specified element or all the elements from the TreeSet collection.


                        import java.util.TreeSet;

                        public class RemoveExample {
                            public static void main(String[] args) {
                                TreeSet<Integer> numbers = new TreeSet<>();
                                numbers.add(2);
                                numbers.add(5);
                                numbers.add(6);
                                System.out.println("TreeSet: " + numbers);

                                // Using the remove() method
                                boolean value1 = numbers.remove(5);
                                System.out.println("Is 5 removed? " + value1);

                                // Using the removeAll() method
                                boolean value2 = numbers.removeAll(numbers);
                                System.out.println("Are all elements removed? " + value2);
                            }
                        }
                    
first() and last() Methods Example

                        import java.util.TreeSet;

                        class Main {
                            public static void main(String[] args) {
                                TreeSet<Integer> numbers = new TreeSet<>();
                                numbers.add(2);
                                numbers.add(5);
                                numbers.add(6);
                                System.out.println("TreeSet: " + numbers);

                                // Using the first() method
                                int first = numbers.first();
                                System.out.println("First Number: " + first);

                                // Using the last() method
                                int last = numbers.last();
                                System.out.println("Last Number: " + last);
                            }
                        }

                    
ceiling(), floor(), higher() and lower() Method Example

                        import java.util.TreeSet;

                        public class navMethodsExample {
                            public static void main(String[] args) {
                                TreeSet<Integer> numbers = new TreeSet<>();
                                numbers.add(2);
                                numbers.add(5);
                                numbers.add(4);
                                numbers.add(6);
                                System.out.println("TreeSet: " + numbers);

                                // Using higher()
                                System.out.println("Using higher: " + numbers.higher(4));

                                // Using lower()
                                System.out.println("Using lower: " + numbers.lower(4));

                                // Using ceiling()
                                System.out.println("Using ceiling: " + numbers.ceiling(4));

                                // Using floor()
                                System.out.println("Using floor: " + numbers.floor(3));

                            }
                        }
                    
pollfirst() and pollLast() Methods Example

                        import java.util.TreeSet;

                        public class PollNavExamples {
                            public static void main(String[] args) {
                                TreeSet<Integer> numbers = new TreeSet<>();
                                numbers.add(2);
                                numbers.add(5);
                                numbers.add(4);
                                numbers.add(6);
                                System.out.println("TreeSet: " + numbers);
                        
                                // Using pollFirst()
                                System.out.println("Removed First Element: " + numbers.pollFirst());
                        
                                // Using pollLast()
                                System.out.println("Removed Last Element: " + numbers.pollLast());
                        
                                System.out.println("New TreeSet: " + numbers);
                            }
                        }
                    
headSet(), tailSet() and subSet() Methods Example

                        import java.util.TreeSet;

                        public class NavExamples3 {
                            public static void main(String[] args) {
                                TreeSet<Integer> numbers = new TreeSet<>();
                                numbers.add(2);
                                numbers.add(5);
                                numbers.add(4);
                                numbers.add(6);
                                System.out.println("TreeSet: " + numbers);
                        
                                // Using headSet() with default boolean value
                                System.out.println("Using headSet without boolean value: " + numbers.headSet(5));
                        
                                // Using headSet() with specified boolean value
                                System.out.println("Using headSet with boolean value: " + numbers.headSet(5, true));
                            }
                        }
                    
headSet(), tailSet() and subSet() Methods Example

                        import java.util.TreeSet;

                        public class NavExamples3 {
                            public static void main(String[] args) {
                                TreeSet<Integer> numbers = new TreeSet<>();
                                numbers.add(2);
                                numbers.add(5);
                                numbers.add(4);
                                numbers.add(6);
                                System.out.println("TreeSet: " + numbers);
                        
                                // Using headSet() with default boolean value
                                System.out.println("Using headSet without boolean value: " + numbers.headSet(5));
                        
                                // Using headSet() with specified boolean value
                                System.out.println("Using headSet with boolean value: " + numbers.headSet(5, true));

                                // Using tailSet() with default boolean value
                                System.out.println("Using tailSet without boolean value: " + numbers.tailSet(4));

                                // Using tailSet() with specified boolean value
                                System.out.println("Using tailSet with boolean value: " + numbers.tailSet(4, false));

                                // Using subSet() with default boolean value
                                System.out.println("Using subSet without boolean value: " + numbers.subSet(4, 6));

                                // Using subSet() with specified boolean value
                                System.out.println("Using subSet with boolean value: " + numbers.subSet(4, false, 6, true));
                            }
                        }
                    
Union of Sets

To perform the union between two sets, we use the addAll() method.


                        import java.util.TreeSet;;

                        public class UnionOfSetExample {
                            public static void main(String[] args) {
                                TreeSet<Integer> evenNumbers = new TreeSet<>();
                                evenNumbers.add(2);
                                evenNumbers.add(4);
                                System.out.println("TreeSet1: " + evenNumbers);

                                TreeSet<Integer> numbers = new TreeSet<>();
                                numbers.add(1);
                                numbers.add(2);
                                numbers.add(3);
                                System.out.println("TreeSet2: " + numbers);

                                // Union of two sets
                                numbers.addAll(evenNumbers);
                                System.out.println("Union is: " + numbers);

                            }
                        }

                    
Intersection of Sets

To perform the intersection between two sets, we use the retainAll() method.


                        import java.util.TreeSet;;

                        public class IntersectionOfSets {
                            public static void main(String[] args) {
                                TreeSet<Integer> evenNumbers = new TreeSet<>();
                                evenNumbers.add(2);
                                evenNumbers.add(4);
                                System.out.println("TreeSet1: " + evenNumbers);

                                TreeSet<Integer> numbers = new TreeSet<>();
                                numbers.add(1);
                                numbers.add(2);
                                numbers.add(3);
                                System.out.println("TreeSet2: " + numbers);

                                // Intersection of two sets
                                numbers.retainAll(evenNumbers);
                                System.out.println("Intersection is: " + numbers);
                            }
                        }

                    
Difference of Sets

To calculate the difference between the two sets, we can use the removeAll() method.


                        import java.util.TreeSet;;

                        public class DifferenceOfSets {
                            public static void main(String[] args) {
                                TreeSet<Integer> evenNumbers = new TreeSet<>();
                                evenNumbers.add(2);
                                evenNumbers.add(4);
                                System.out.println("TreeSet1: " + evenNumbers);

                                TreeSet<Integer> numbers = new TreeSet<>();
                                numbers.add(1);
                                numbers.add(2);
                                numbers.add(3);
                                numbers.add(4);
                                System.out.println("TreeSet2: " + numbers);

                                // Difference between two sets
                                numbers.removeAll(evenNumbers);
                                System.out.println("Difference is: " + numbers);
                            }
                        }

                    
Subset of a Set

To check if a set is a subset of another set or not, we use the containsAll() method.


                        import java.util.TreeSet;

                        public class SubsetOfSet {
                            public static void main(String[] args) {
                                TreeSet<Integer> numbers = new TreeSet<>();
                                numbers.add(1);
                                numbers.add(2);
                                numbers.add(3);
                                numbers.add(4);
                                System.out.println("TreeSet1: " + numbers);

                                TreeSet<Integer> primeNumbers = new TreeSet<>();
                                primeNumbers.add(2);
                                primeNumbers.add(3);
                                System.out.println("TreeSet2: " + primeNumbers);

                                // Check if primeNumbers is subset of numbers
                                boolean result = numbers.containsAll(primeNumbers);
                                System.out.println("Is TreeSet2 subset of TreeSet1? " + result);
                            }
                        }