Java TreeSet tutorial with examples will help you understand how to use Java TreeSet in an easy way. TreeSet in Java is a Set implementation based on the TreeMap. Unlike HashMap, the elements of the TreeSet are ordered using their natural ordering. Also, unlike the Map implementations, for example, TreeMap or HashMap, the TreeSet does not maintain key value pairs but offers the uniqueness of its elements.
If you do not want to sort the TreeSet elements using their natural ordering, you can provide a custom Comparator when you create the TreeSet object using the below given constructor.
1 |
public TreeSet(Comparator comparator) |
The TreeSet in Java provides log(n) time cost for the add
, remove
and contains
operations.
The TreeSet implementation is not synchronized. That means if multiple threads are trying to modify the TreeSet object at the same time then the access must be synchronized explicitly. If this is the case, you can either synchronize the TreeSet object or you can get the synchronized SortedSet object from the existing TreeSet using synchronizedSortedSet
method of the Collections class as given below.
1 |
SortedSet sortedSet = Collections.synchronizedSortedSet(existingTreeSetObject); |
The Iterator object obtained by the iterator
method of the TreeSet is fail-fast. That means if the TreeSet object is structurally modified after obtaining the iterator (except by using iterator’s own remove
method), calling any methods of the iterator object will throw ConcurrentModificationException
.
How to create a new TreeSet object?
The TreeSet class in Java provides several constructors using which we can create new TreeSet objects.
1. How to create a new empty TreeSet object?
The default constructor of the TreeSet class creates a new empty TreeSet object.
1 |
TreeSet<String> tSetColors = new TreeSet<String>(); |
The elements added to this set will be sorted by the natural ordering of the elements.
2. How to create a new TreeSet object with a custom Comparator?
If you want to specify a custom Comparator instead of using the default natural ordering, you can do so by using the overloaded constructor with the Comparator parameter.
1 |
public TreeSet(Comparator<? super E> comparator) |
The elements added to this set will be ordered by the specified comparator.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
class DescendingNumberComparator implements Comparator<Integer>{ /* * This comparator will sort integer objects in the * descending order */ public int compare(Integer i1, Integer i2) { return i2 - i1; } } public class Example { public static void main(String[] args) { /* * TreeSet using the default natural ordering */ TreeSet<Integer> tSetNumbers = new TreeSet<Integer>(); tSetNumbers.add(3); tSetNumbers.add(1); tSetNumbers.add(4); tSetNumbers.add(2); //The default order i.e. ascending System.out.println("Default TreeSet elements: " + tSetNumbers); /* * Create new TreeSet using the custom comparator */ TreeSet<Integer> tSetDescendingNumbers = new TreeSet<Integer>(new DescendingNumberComparator()); tSetDescendingNumbers.add(3); tSetDescendingNumbers.add(1); tSetDescendingNumbers.add(4); tSetDescendingNumbers.add(2); //Numbers will sorted in descending order defined by comparator System.out.println("Custom Comparator TreeSet elements: " + tSetDescendingNumbers); } } |
Output
1 2 |
Default TreeSet elements: [1, 2, 3, 4] Custom Comparator TreeSet elements: [4, 3, 2, 1] |
3. How to create a new TreeSet object from another Collection object?
The below given overridden constructor of the TreeSet class creates a new TreeSet object containing the elements from the specified Collection object.
1 |
public TreeSet(Collection<? extends E> collection) |
The elements added from another collection object are sorted automatically in the natural order of the elements. The below given example shows how to create a TreeSet object from an ArrayList object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
//create new ArrayList List<Integer> list = new ArrayList<Integer>(); list.add(3); list.add(1); list.add(2); System.out.println("ArrayList contains: " + list); /* * Create TreeSet from ArrayList using the constructor */ TreeSet<Integer> tSetNumbers = new TreeSet<Integer>(list); System.out.println("TreeSet contains: " + tSetNumbers); |
Output
1 2 |
ArrayList contains: [3, 1, 2] TreeSet contains: [1, 2, 3] |
As you can see from the output, the elements added to the TreeSet are automatically sorted in the natural ordering of the elements, which is ascending order for the Integer objects.
Java TreeSet Methods
How to add elements to TreeSet using the add and addAll methods?
The add
method of the TreeSet class in Java adds the specified element to the TreeSet only if it is not present and returns true. If the specified element already exists in the TreeSet, the add
method does not add the element and returns false.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
TreeSet<String> tSetColors = new TreeSet<String>(); /* * To add elements to TreeSet, use the * add method. */ //this will add "Red" to the TreeSet, returns true System.out.println( tSetColors.add("Red") ); //this will add "Green" and return true System.out.println( tSetColors.add("Green") ); //this will NOT add "Red" as it already exists, and returns false System.out.println( tSetColors.add("Red") ); System.out.println("TreeSet contains: " + tSetColors); |
Output
1 2 3 4 |
true true false TreeSet contains: [Green, Red] |
How to add elements from other Collection to the TreeSet?
The addAll
method adds the elements from the specified Collection to this TreeSet object. It returns true if the TreeSet was changed, false otherwise.
1 |
public boolean addAll(Collection<? extends E> collection) |
The below given example shows how to add all elements of an ArrayList to the TreeSet.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
//create new ArrayList List<String> list = new ArrayList<String>(); list.add("Red"); list.add("Green"); list.add("Blue"); //Create new TreeSet TreeSet<String> tSetColors = new TreeSet<String>(); tSetColors.add("Red"); tSetColors.add("Green"); /* * add all ArrayList elements to the TreeSet using the * addAll method. * * Remember, elements which are not already present will * be added to the TreeSet. So "Red", and "Green" will not * be added, but "Blue" will. */ tSetColors.addAll(list); System.out.println("TreeSet contains: " + tSetColors); |
Output
1 |
TreeSet contains: [Blue, Green, Red] |
As you can see from the output, only elements that are not already present in the TreeSet are added to it.
How to get elements from the TreeSet?
1. How to get the first element from the TreeSet using the first method?
The first
method of the TreeSet class in Java returns the first or the lowest element in the TreeSet.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
TreeSet<Integer> tSetNumbers = new TreeSet<Integer>(); tSetNumbers.add(3); tSetNumbers.add(2); tSetNumbers.add(1); tSetNumbers.add(4); /* * To get the first element of the TreeSet, use the * first method. * * Remember, elements of the TreeSet are sorted, so it is * not necessary that the element which was added first will * also be the first element in the TreeSet. */ //this will not return 3, but 1, as it is the lowest element System.out.println("TreeSet first element: " + tSetNumbers.first()); |
Output
1 |
TreeSet first element: 1 |
2. How to get the last element from the TreeSet using the last method?
Just like the first
method, the last
method of the TreeSet class returns the last element or the largest element of the TreeSet.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
TreeSet<Integer> tSetNumbers = new TreeSet<Integer>(); tSetNumbers.add(3); tSetNumbers.add(1); tSetNumbers.add(4); tSetNumbers.add(2); /* * To get the last element of the TreeSet, use the * last method. * * Remember, elements of the TreeSet are sorted, so it is * not necessary that the element which was added last will * also be the last element in the TreeSet. */ //this will not return 2, but 4, as it is the largest element System.out.println("TreeSet last element: " + tSetNumbers.last()); |
Output
1 |
TreeSet first element: 4 |
3. How to get an element which is higher than the specified element from the TreeSet?
How to get a higher element using the higher method?
The higher
method of the TreeSet class returns the smallest element from the TreeSet which is greater than the specified element. If there is no such element in the TreeSet, it returns null.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
TreeSet<Integer> tSetNumbers = new TreeSet<Integer>(); tSetNumbers.add(3); tSetNumbers.add(1); tSetNumbers.add(4); tSetNumbers.add(2); /* * To get the element which is greater than the specified element, * use the higher method. */ //this will print "3" System.out.println( tSetNumbers.higher(2) ); /* * this will print null, as there is no element * which is higher than "4" in the TreeSet */ System.out.println( tSetNumbers.higher(4) ); |
Output
1 2 |
3 null |
How to get a higher element using the ceiling method?
The ceiling
method returns the smallest element from the TreeSet which is greater than or equal to the specified element. It returns null if no such element exists in the TreeSet.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
TreeSet<Integer> tSetNumbers = new TreeSet<Integer>(); tSetNumbers.add(3); tSetNumbers.add(1); tSetNumbers.add(4); tSetNumbers.add(2); /* * To get the smallest element which is greater than or * equal to the specified element, use the ceiling method. */ //this will print "2" System.out.println( tSetNumbers.ceiling(2) ); /* * Unlike the higher method, this will not print null * as it returns the smallest element which is greater than * or equal to the specified element which is 4 */ System.out.println( tSetNumbers.ceiling(4) ); //this will print null, as no element is >= 5 in the TreeSet System.out.println( tSetNumbers.ceiling(5) ); |
Output
1 2 3 |
2 4 null |
Difference between higher and ceiling methods: The higher
method returns the smallest element that is strictly greater than the specified element. While the ceiling
method returns the smallest element which is greater than or equal to the specified element.
4. How to get an element which is lower than the specified element from the TreeSet?
How to get a lower element using the lower method?
The lower
method of the TreeSet class returns the greatest element from the TreeSet which is less than the specified element. If there is no such element in the TreeSet, it returns null.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
TreeSet<Integer> tSetNumbers = new TreeSet<Integer>(); tSetNumbers.add(3); tSetNumbers.add(1); tSetNumbers.add(4); tSetNumbers.add(2); /* * To get the greatest element which is less than the specified element, * use the lower method. */ //this will print "2" System.out.println( tSetNumbers.lower(2) ); /* * this will print null, as there is no element * which is < 1 in the TreeSet */ System.out.println( tSetNumbers.lower(1) ); |
Output
1 2 |
1 null |
How to get a lower element using the floor method?
The floor
method returns the greatest element from the TreeSet which is less than or equal to the specified element. It returns null if no such element exists in the TreeSet.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
tSetNumbers.add(3); tSetNumbers.add(1); tSetNumbers.add(4); tSetNumbers.add(2); /* * To get the largest element which is less than or * equal to the specified element, use the floor method. */ //this will print "2" System.out.println( tSetNumbers.floor(2) ); /* * Unlike the lower method, this will not print null * as it returns the largest element which is greater than * or equal to the specified element which is 1 */ System.out.println( tSetNumbers.floor(1) ); //this will print null, as no element is <= 0 in the TreeSet System.out.println( tSetNumbers.floor(0) ); |
Output
1 2 3 |
2 1 null |
Difference between lower and floor methods: The lower
method returns the greatest element that is strictly less than the specified element. While the floor
method returns the greatest element which is less than or equal to the specified element.
How to get the size of the TreeSet using the size method?
The size
method of the TreeSet class returns the number of elements that are stored in the TreeSet object. It returns 0 if the TreeSet is empty.
1 2 3 4 5 6 7 8 9 10 |
TreeSet<Integer> tSetNumbers = new TreeSet<Integer>(); //will print 0 as the TreeSet is empty System.out.println( "TreeSet size: " + tSetNumbers.size() ); tSetNumbers.add(1); tSetNumbers.add(2); //will print 2 as there are 2 elements in the TreeSet System.out.println( "TreeSet size: " + tSetNumbers.size() ); |
Output
1 2 |
TreeSet size: 0 TreeSet size: 2 |
How to check if the TreeSet is empty using the isEmpty method?
The isEmpty
method of the TreeSet class returns true if there are no elements in the TreeSet object. It returns false if there is at least one element in it.
1 2 3 4 5 6 7 8 9 |
TreeSet<Integer> tSetNumbers = new TreeSet<Integer>(); //will print true as the TreeSet is empty System.out.println( "TreeSet is empty: " + tSetNumbers.isEmpty() ); tSetNumbers.add(1); //will print false as there is one element in the TreeSet System.out.println( "TreeSet is empty: " + tSetNumbers.isEmpty() ); |
Output
1 2 |
TreeSet is empty: true TreeSet is empty: false |
Similarly, you can also compare the TreeSet size with 0 to check if the TreeSet is empty. However, using the isEmpty
method is recommended way as it clearly states the purpose of the code and is more readable.
How to check if the TreeSet contains the specified element using the contains method?
The contains
method of the TreeSet class returns true if the TreeSet contains the specified element. It returns false otherwise.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
TreeSet<String> tSetColors = new TreeSet<String>(); tSetColors.add("Red"); tSetColors.add("Green"); tSetColors.add("Blue"); /* * Use the contains method to check if the TreeSet contains an element. */ //this will print true, as the "Red" is present in the TreeSet System.out.println( tSetColors.contains("Red") ); //this will print false, as the TreeSet does not contain the "Yellow" System.out.println( tSetColors.contains("Yellow") ); |
Output
1 2 |
true false |
The contains method throws ClassCastException
if the specified element cannot be compared with the elements contained in the TreeSet. It also throws NullPointerException
if the specified element is null.
How to Iterate Java TreeSet?
You can iterate TreeSet elements using the iterator with while loop or using the enhanced for loop.
1. Iterate over TreeSet elements using the Iterator
The iterator
method of the TreeSet class returns an iterator over the TreeSet elements. To iterate the elements, use hasNext
and next
methods of the iterator object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
TreeSet<Integer> tSetNumbers = new TreeSet<Integer>(); tSetNumbers.add(3); tSetNumbers.add(1); tSetNumbers.add(4); tSetNumbers.add(2); //get an iterator using the iterator method Iterator<Integer> iterator = tSetNumbers.iterator(); /* * Use while loop along with the * hasNext and next methods to iterate over the elements * of the TreeSet */ System.out.println("TreeSet Iterator: "); while(iterator.hasNext()){ System.out.println(iterator.next()); } |
Output
1 2 3 4 5 |
TreeSet Iterator: 1 2 3 4 |
2. Iterate over TreeSet using the enhanced for loop
You can also use the enhanced for loop to iterate through the TreeSet elements.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
TreeSet<Integer> tSetNumbers = new TreeSet<Integer>(); tSetNumbers.add(3); tSetNumbers.add(1); tSetNumbers.add(4); tSetNumbers.add(2); /* * Iterate through TreeSet using the for loop */ System.out.println("Iterate TreeSet using for loop: "); for(Integer i : tSetNumbers){ System.out.println(i); } |
Output
1 2 3 4 5 |
Iterate TreeSet using for loop: 1 2 3 4 |
How to iterate TreeSet in reverse order?
The descendingIterator
method returns an iterator over the elements of the TreeSet in descending order.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
TreeSet<Integer> tSetNumbers = new TreeSet<Integer>(); tSetNumbers.add(3); tSetNumbers.add(1); tSetNumbers.add(4); tSetNumbers.add(2); /* * To iterate over TreeSet in descending order or reverse direction, use the * descendingIterator method. * */ Iterator<Integer> reverseIterator = tSetNumbers.descendingIterator(); System.out.println("Iterating TreeSet in reverse direction: "); //iterate in backwards direction or reverse direction while(reverseIterator.hasNext()){ System.out.println(reverseIterator.next()); } |
Output
1 2 3 4 5 |
Iterating TreeSet in reverse direction: 4 3 2 1 |
How to remove elements from the TreeSet?
1. How to remove an element from the TreeSet using the remove method?
The remove
method removes the specified element from the TreeSet. The remove
method returns true if the set contained the specified element and it was removed. If set does not contain the specified element, it returns false.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
TreeSet<String> tSetColors = new TreeSet<String>(); tSetColors.add("Red"); tSetColors.add("Green"); tSetColors.add("Blue"); /* * To remove an element from the TreeSet, use the * remove method. */ //this removes "Red" and returns true System.out.println( tSetColors.remove("Red") ); //this will return false, as the TreeSet does not contain "Purple" System.out.println( tSetColors.remove("Purple") ); System.out.println("TreeSet contains: " + tSetColors); |
Output
1 2 3 |
true false TreeSet contains: [Blue, Green] |
2. How to remove all elements from the TreeSet using the clear method?
The clear
method of the TreeSet class removes all the elements from the TreeSet or empty the TreeSet object. The TreeSet will be empty after the method call.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
TreeSet<String> tSetColors = new TreeSet<String>(); tSetColors.add("Red"); tSetColors.add("Green"); tSetColors.add("Blue"); System.out.println("TreeSet contains " + tSetColors.size() + " elements."); /* * To remove all elements from the TreeSet, use the * clear method. */ tSetColors.clear(); System.out.println( "TreeSet is empty: " + tSetColors.isEmpty() ); |
Output
1 2 |
TreeSet contains 3 elements. TreeSet is empty: true |
3. How to remove the first element from the TreeSet using the pollFirst method?
The pollFirst
method of the TreeSet class returns and removes the first element of the TreeSet. It returns null if the TreeSet is empty.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
TreeSet<Integer> tSetNumbers = new TreeSet<Integer>(); tSetNumbers.add(3); tSetNumbers.add(1); tSetNumbers.add(4); tSetNumbers.add(2); /* * To remove the first element from the TreeSet, use the * pollFirst method. * * Remember, the TreeSet is sorted, so the first element might * be different from the element that was added first. */ //This will return and remove the "1" element, not "3" System.out.println( tSetNumbers.pollFirst() ); System.out.println("TreeSet contains: " + tSetNumbers); |
Output
1 2 |
1 TreeSet contains: [2, 3, 4] |
4. How to remove the last element from the TreeSet using the pollLast method?
Just like the pollFirst
method, the pollLast
method returns and removes the last element from the TreeSet. It returns null if the set is empty.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
TreeSet<Integer> tSetNumbers = new TreeSet<Integer>(); tSetNumbers.add(3); tSetNumbers.add(1); tSetNumbers.add(4); tSetNumbers.add(2); /* * To remove the last element from the TreeSet, use the * pollLast method. * * Remember, the TreeSet is sorted, so the last element might * be different from the element that was added last. */ //This will return and remove the "4" element, not "3" System.out.println( tSetNumbers.pollLast() ); System.out.println("TreeSet contains: " + tSetNumbers); |
Output
1 2 |
4 TreeSet contains: [1, 2, 3] |
5. How to remove an element from the TreeSet using the Iterator?
The remove
method of the Iterator removes the current element from the underlying TreeSet object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
TreeSet<Integer> tSetNumbers = new TreeSet<Integer>(); tSetNumbers.add(3); tSetNumbers.add(1); tSetNumbers.add(4); tSetNumbers.add(5); tSetNumbers.add(2); //get an iterator using the iterator method Iterator<Integer> iterator = tSetNumbers.iterator(); while(iterator.hasNext()){ Integer temp = iterator.next(); if( temp.equals( new Integer(1) ) ){ /* * Use remove method the Iterator * class to remove the current element * from the TreeSet */ iterator.remove(); } } System.out.println( "TreeSet contains: " + tSetNumbers); |
Output
1 |
TreeSet contains: [2, 3, 4, 5] |
How to get the subset from the TreeSet?
1. How to get the subset from TreeSet using the subset method?
The subSet
method of the TreeSet class returns a portion of the TreeSet whose elements range from the startElement to endElement.
1 |
SortedSet<E> subSet(E startElement, E endElement) |
The startElement is inclusive (i.e. included in the subset), while the endElement is exclusive (not included in the subset).
Subset Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
TreeSet<Integer> tSetNumbers = new TreeSet<Integer>(); tSetNumbers.add(3); tSetNumbers.add(1); tSetNumbers.add(4); tSetNumbers.add(5); tSetNumbers.add(2); /* * To get the subset of the TreeSet, use the * subSet method and specify the start and end elements. */ Set<Integer> subset = tSetNumbers.subSet(2,5); //2 is included while 5 is not System.out.println( "TreeSet subset contains: " + subset ); |
Output
1 |
TreeSet subset contains: [2, 3, 4] |
If you want to control the inclusiveness of the start and end elements, use an overloaded subSet
method.
1 |
NavigableSet<E> subSet(E startElement, boolean startElementInclusive, E endElement, boolean endElementInclusive) |
If the startElementInclusive parameter is true, the startElement will be included in the subset. Similarly, if the endElementInclusive parameter is true, the endElement will be included in the subset.
The subset returned from these methods are backed by the original TreeSet. If you make any changes to the subset, it will be reflected back to the TreeSet, and vice versa.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
TreeSet<Integer> tSetNumbers = new TreeSet<Integer>(); tSetNumbers.add(3); tSetNumbers.add(1); tSetNumbers.add(4); tSetNumbers.add(5); tSetNumbers.add(2); //get the subset Set<Integer> subset = tSetNumbers.subSet(2,5); //remove an element from the subset subset.remove(2); //the change will reflect back in the TreeSet too! System.out.println("TreeSet contains: " + tSetNumbers); |
Output
1 |
TreeSet contains: [1, 3, 4, 5] |
2. How to get a subset containing elements higher than the specified element from the TreeSet?
The tailSet
method of the TreeSet class returns a subset whose elements are greater than or equal to the specified element.
1 |
public SortedSet<E> tailSet(E startElement) |
Just like the subSet
method, The subset returned from this method is backed by the original TreeSet, so any changes you make to the subset will also be reflected back to the original TreeSet.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
TreeSet<Integer> tSetNumbers = new TreeSet<Integer>(); tSetNumbers.add(3); tSetNumbers.add(1); tSetNumbers.add(4); tSetNumbers.add(5); tSetNumbers.add(2); /* * to get the tail set, use the * tailSet method. * * Elements of the subset will be greater than * or equal to the specified element. */ Set<Integer> subset = tSetNumbers.tailSet(2); //will contains 2, 3, 4, 5 System.out.println( "tail set contains: " + subset ); |
Output
1 |
tail set contains: [2, 3, 4, 5] |
As you can see from the output, the start element is included in the subset. If you want to exclude it, use an overloaded tailSet
method with the boolean parameter.
1 |
public NavigableSet<E> tailSet(E startElement, boolean startElementInclusive) |
3. How to get a subset containing elements lower than the specified element from the TreeSet?
The headSet
method of the TreeSet class returns a portion or the subset of the TreeSet whose elements are lower than the specified element.
1 |
public SortedSet<E> headSet(E endEement) |
The headset returned by this method is backed by the original TreeSet object. Any changes you make to the subset, it will be reflected back to the TreeSet object, and vice versa.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
TreeSet<Integer> tSetNumbers = new TreeSet<Integer>(); tSetNumbers.add(3); tSetNumbers.add(1); tSetNumbers.add(4); tSetNumbers.add(5); tSetNumbers.add(2); /* * to get the head set, use the * headSet method. * * Elements of the subset will be less than * the specified end element. */ Set<Integer> subset = tSetNumbers.headSet(3); //will contains 1,2 not 3 System.out.println( "head set contains: " + subset ); |
Output
1 |
head set contains: [1, 2] |
As you can see from the output, the end element is not included by default. If you want to include it, use an overloaded headSet
method with the boolean parameter.
1 |
public NavigableSet<E> headSet(E endElement, boolean endElementInclude) |
How to reverse the TreeSet using the descendingSet method?
The descendingSet
method of the TreeSet class returns a view of the TreeSet elements in the reverse order.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
TreeSet<Integer> tSetNumbers = new TreeSet<Integer>(); tSetNumbers.add(3); tSetNumbers.add(1); tSetNumbers.add(4); tSetNumbers.add(5); tSetNumbers.add(2); /* * To reverse the TreeSet, use the * descendingSet method. */ Set<Integer> reverseSet = tSetNumbers.descendingSet(); System.out.println("TreeSet Reverse view: " + reverseSet); /* * The reverse set is backed by the original TreeSet. * Any changes you make to the reverse set, it will * be reflected back to the original TreeSet, and vice versa. */ //remove an element from the reverse set reverseSet.remove(2); //The TreeSet will reflect the changes too System.out.println("TreeSet contains: " + tSetNumbers); |
Output
1 2 |
TreeSet Reverse view: [5, 4, 3, 2, 1] TreeSet contains: [1, 3, 4, 5] |
How to convert TreeSet to an array using the toArray method?
The toArray
method of the TreeSet class returns an array containing all the elements of the TreeSet object.
1 |
public <T> T[] toArray(T[] array) |
If the specified array is big enough to contain all the elements of the TreeSet, the toArray
method returns the same array with the TreeSet elements. If not, a new array is created and returned with the TreeSet elements. If the specified array is larger than the size of the TreeSet, the array element that immediately comes after the TreeSet elements is set to null.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
TreeSet<Integer> tSetNumbers = new TreeSet<Integer>(); tSetNumbers.add(3); tSetNumbers.add(1); tSetNumbers.add(4); tSetNumbers.add(5); tSetNumbers.add(2); //create an array of same type having the same size of the TreeSet Integer[] array = new Integer[ tSetNumbers.size() ]; /* * To convert TreeSet to array, use the * toArray method. */ array = tSetNumbers.toArray(array); System.out.println("Convert TreeSet to array: "); System.out.println( Arrays.toString(array) ); |
Output
1 2 |
Convert TreeSet to array: [1, 2, 3, 4, 5] |
You can pass an array of any length to the toArray
method. However, it is recommended to pass an array having the same size as the TreeSet object to avoid the performance penalty of allocation of a new array.
How to use the retainAll, removeAll, containsAll, and addAll methods of the TreeSet in Java?
How to remove all the common elements of two TreeSet objects using the removeAll method?
The removeAll
method removes all the elements from this TreeSet object that are also present in the specified Collection object.
1 |
public boolean removeAll(Collection<?> collection) |
The removeAll
method returns true if this TreeSet object is changed after the method call.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
TreeSet<Integer> tSetNumbers = new TreeSet<Integer>(); tSetNumbers.add(3); tSetNumbers.add(1); tSetNumbers.add(4); tSetNumbers.add(5); tSetNumbers.add(2); TreeSet<Integer> tSetOddNumbers = new TreeSet<Integer>(); tSetOddNumbers.add(1); tSetOddNumbers.add(3); tSetOddNumbers.add(5); /* * To remove all the common elements of the two TreeSet objects, use the * removeAll method */ //this will remove all the odd numbers from the TreeSet tSetNumbers.removeAll(tSetOddNumbers); //modified set System.out.println("TreeSet remove common elements: " + tSetNumbers); |
Output
1 |
TreeSet remove common elements: [2, 4] |
As you can see from the output, all the common elements between two set objects are removed from the TreeSet object. The removeAll
method is not restricted only to the TreeSet type, as it accepts any Collection type like ArrayList as well.
How to get an intersection of two TreeSet objects using the retainAll method?
The retainAll
method removes all the elements from this TreeSet object that are not present in the specified Collection object, thus keeping only the common elements or an intersection of the two TreeSet objects.
1 |
public boolean retainAll(Collection<?> collection) |
The retainAll
method returns true if this TreeSet object is changed after the method call.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
TreeSet<Integer> tSetNumbers = new TreeSet<Integer>(); tSetNumbers.add(3); tSetNumbers.add(1); tSetNumbers.add(4); tSetNumbers.add(5); tSetNumbers.add(2); TreeSet<Integer> tSetOddNumbers = new TreeSet<Integer>(); tSetOddNumbers.add(1); tSetOddNumbers.add(3); tSetOddNumbers.add(5); /* * To get the intersection of two TreeSet objects, use the * retainAll method */ //this will remove all the even numbers from the TreeSet tSetNumbers.retainAll(tSetOddNumbers); //modified set System.out.println("TreeSet intersection: " + tSetNumbers); |
Output
1 |
TreeSet intersection: [1, 3, 5] |
As you can see from the output, only the common elements between two set objects are kept in the TreeSet and that leaves the intersection of two TreeSet objects. The retainAll
method is not restricted only to the TreeSet, as it accepts any Collection type like ArrayList as well.
How to get a union of two TreeSet objects using the addAll method?
The addAll
method of the TreeSet class adds all the elements of the specified TreeSet object to this object. As the TreeSet contains the unique elements, only elements that are missing from this TreeSet objects are added.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
TreeSet<Integer> tSetNumbers = new TreeSet<Integer>(); tSetNumbers.add(3); tSetNumbers.add(1); tSetNumbers.add(4); tSetNumbers.add(5); tSetNumbers.add(2); TreeSet<Integer> tSetOther = new TreeSet<Integer>(); tSetOther.add(5); tSetOther.add(6); tSetOther.add(7); /* * To get the union of two TreeSet objects, use the * addAll method */ /* * this will add all the missing elements from * the tSetOther to the tSetNumbers object, thus * creating a union of two TreeSet objects. */ tSetNumbers.addAll(tSetOther); //modified set System.out.println("Union of two TreeSet objects: " + tSetNumbers); |
Output
1 |
Union of two TreeSet objects: [1, 2, 3, 4, 5, 6, 7] |
As you can see from the output, the TreeSet now contains all the elements present in both the objects. The addAll
method accepts the Collection type as a parameter, so you can get a union of TreeSet and ArrayList objects as well.
How to check if a TreeSet object contains all the elements of another TreeSet object?
The containsAll
method of the TreeSet object returns true of this TreeSet object contains all the elements of the specified another TreeSet object. It returns false otherwise.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
TreeSet<Integer> tSetNumbers = new TreeSet<Integer>(); tSetNumbers.add(3); tSetNumbers.add(1); tSetNumbers.add(2); TreeSet<Integer> tSetOther = new TreeSet<Integer>(); tSetOther.add(1); tSetOther.add(2); tSetOther.add(3); /* * To check if this TreeSet contains all the elements of another TreeSet, * use the containsAll method. */ /* * This will print true as tSetNumbers contains all the * elements of the tSetOther. */ System.out.println( tSetNumbers.containsAll(tSetOther) ); //add one more element to other TreeSet tSetOther.add(4); //now this will print false, as 4 is missing from the tSetNumbers System.out.println( tSetNumbers.containsAll(tSetOther) ); |
Output
1 2 |
true false |
As the containsAll
method accepts the Collection type, you can compare elements of the TreeSet with any Collection type like ArrayList.
How to clone a TreeSet object?
The clone
method of the TreeSet returns a shallow copy of this TreeSet object. The returned object is not deeply cloned, i.e. only element references are cloned, not the actual objects.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
class LaptopBrand implements Comparable<LaptopBrand>{ private String name; public LaptopBrand(String name){ this.setName(name); } public String getName() { return name; } public void setName(String name) { this.name = name; } public int compareTo(LaptopBrand o) { return name.compareTo(o.getName()); } public String toString(){ return this.getName(); } } public class Example { public static void main(String[] args) { TreeSet<LaptopBrand> tSetBrands = new TreeSet<LaptopBrand>(); tSetBrands.add( new LaptopBrand("Asus") ); tSetBrands.add( new LaptopBrand("Apple") ); tSetBrands.add( new LaptopBrand("Lenovo") ); /* * To clone the TreeSet, use the clone method */ TreeSet<LaptopBrand> tSetClonedBrands = (TreeSet<LaptopBrand>) tSetBrands.clone(); System.out.println("Original TreeSet contains: " + tSetBrands); System.out.println("Cloned TreeSet contains: " + tSetClonedBrands); /* * The clone method returns a shallow copy of the TreeSet. * Only object references are copied, not the actual objects. That means * if you change any object, it will be changed in both the TreeSet objects */ //change first element in the original TreeSet tSetBrands.first().setName("CHANGED_NAME"); System.out.println("After changing an element"); System.out.println("Original TreeSet contains: " + tSetBrands); System.out.println("Cloned TreeSet contains: " + tSetClonedBrands); /* * However, adding or removing elements from either * TreeSet does not change both of them */ //add element to original TreeSet tSetBrands.add( new LaptopBrand("HP") ); System.out.println("After adding an element"); System.out.println("Original TreeSet contains: " + tSetBrands); System.out.println("Cloned TreeSet contains: " + tSetClonedBrands); //remove an element from cloned TreeSet tSetClonedBrands.remove( new LaptopBrand("Asus") ); System.out.println("After removing an element"); System.out.println("Original TreeSet contains: " + tSetBrands); System.out.println("Cloned TreeSet contains: " + tSetClonedBrands); } } |
Output
1 2 3 4 5 6 7 8 9 10 11 |
Original TreeSet contains: [Apple, Asus, Lenovo] Cloned TreeSet contains: [Apple, Asus, Lenovo] After changing an element Original TreeSet contains: [CHANGED_NAME, Asus, Lenovo] Cloned TreeSet contains: [CHANGED_NAME, Asus, Lenovo] After adding an element Original TreeSet contains: [CHANGED_NAME, Asus, HP, Lenovo] Cloned TreeSet contains: [CHANGED_NAME, Asus, Lenovo] After removing an element Original TreeSet contains: [CHANGED_NAME, Asus, HP, Lenovo] Cloned TreeSet contains: [CHANGED_NAME, Lenovo] |
As you can see from the output, when we changed an element in the original TreeSet object, the change is reflected in the cloned TreeSet object as well. That is because both of the TreeSet objects refer to the same elements. However, adding or removing the elements from either the TreeSet objects does not affect the other TreeSet.
Below given are some of the TreeSet examples which show how to use TreeSet in Java.
Java TreeSet Examples
- How to create new objects of TreeSet using the constructors
- How to add elements to TreeSet
- How to fix Java TreeSet java.lang.ClassCastExcpetion exception
- How to print TreeSet elements in Java
- How to get size of the TreeSet object (length)
- How to iterate TreeSet in Java
- How to get the first and last elements of the TreeSet
- How to remove elements from Java TreeSet
- How to clear TreeSet (remove all elements)
- How to check if element exists in TreeSet (TreeSet contains)
- How to find index of the element in TreeSet
- How to get elements by index from Java TreeSet
- How to check if TreeSet is empty (isEmpty method)
- How to compare two TreeSet objects using the equals method
- How to get headset, tailset, and subset from the Java TreeSet
- How to copy, merge, or clone the TreeSet in Java
- How to get floor or ceiling values from Java TreeSet
- How to reverse order of the TreeSet elements (iterate TreeSet in reverse order)
- How to get a union or intersection of two TreeSet objects
- How to convert an array to TreeSet
- How to convert TreeSet to an array
- How to convert HashSet to TreeSet in Java
- How to convert TreeSet to ArrayList or LinkedList (List)
- How to convert ArrayList to TreeSet
References:
Java TreeSet class Javadoc
Please let me know if you liked the Java TreeSet tutorial with examples in the comments section below.