In Java Tree Set is a data structure available in the java collection framework.
What is Tree Set
A TreeSet is a implementation of NavigableSet in java, which means TreeSet is a sorted, navigable set of element. TreeSet data structure is based on red black tree data structure.
Properties of TreeSet
- Duplicate objects are not allowed
- Insertion order not preserved
- Heterogeneous objects are not allowed
- Null insertion is possible but at most one.
- All elements in TreeSet are sorted in natural order or according to some specified comparator.
TreeSet Java Example
import java.util.TreeSet;
public class TreeSetDemo {
public static void main(String[] args) {
TreeSet<Integer> treeSet = new TreeSet<>();
// Adding elements in the TreeSet
treeSet.add(12);
treeSet.add(42);
treeSet.add(26);
treeSet.add(2);
// printing the TreeSet element(sorted element)
System.out.println(treeSet);
// removing elements from TreeSet
treeSet.remove(12);
// updated TreeSet
System.out.println(treeSet);
}
}
![TreeSet Java Example](https://thecodedata.com/wp-content/uploads/2023/09/image-5.png)
3 thoughts on “TreeSet in Java”