TreeSet
Obtain sub Set from TreeSet example
In this example we shall show you how to obtain a sub set from a TreeSet. We will use the subSet(E fromElement, E toElement)
API method of TreeSet. To obtain a sub set from a TreeSet, one should perform the following steps:
- Create a new TreeSet.
- Populate the set with elements, with
add(E e)
API method of TreeSet. - Invoke the
subSet(E fromElement, E toElement)
API method of TreeSet to get a sub Set of the original TreeSet. The SortedSet that is returned contains elements from fromElement to toElement – 1 of the original TreeSet. - Note that the sub Set is backed by the original TreeSet. So any changes made to sub set will also be reflected to the original TreeSet. To check if this is true, we can remove an element from the sub set and then check if it exists in the original TreeSet,
as described in the code snippet below.
package com.javacodegeeks.snippets.core; import java.util.TreeSet; import java.util.SortedSet; public class SubSetTreeSet { public static void main(String[] args) { // Create a TreeSet and populate it with elements TreeSet treeSet = new TreeSet(); treeSet.add("element_1"); treeSet.add("element_3"); treeSet.add("element_2"); treeSet.add("element_4"); treeSet.add("element_5"); /* Use the SortedSet subSet(Object fromElement, Object toElement) operation to get a sub Set of the original TreeSet. This method returns an SortedSet object containing elements from fromElement to toElement - 1 of the original TreeSet */ SortedSet sortedSet = treeSet.subSet("element_2","element_5"); System.out.println("SortedSet Contains : " + sortedSet); /* Sub Set returned is backed by original TreeSet. So any changes made to sub set will also be reflected to the original TreeSet. We will test that by removing an element from the sub set and check that it is removed from the original TreeSet also */ boolean result = sortedSet.remove("element_3"); System.out.println("element_3 is removed from sub set : " + result); System.out.println("Elements in TreeSet : " + treeSet); } }
Output:
SortedSet Contains : [element_2, element_3, element_4]
element_3 is removed from sub set : true
Elements in TreeSet : [element_1, element_2, element_4, element_5]
This was an example of how to obtain a sub set from a TreeSet in Java.