What is TreeSet?
- Stores unique elements.
- Maintains elements in sorted order (ascending by default).
- Does not allow duplicates.
- It is part of the Java Collections Framework in Java and implements the Set interface.
Example :
import java.util.TreeSet;
public class Learn {
public static void main(String[] args) {
TreeSet tr = new TreeSet();
tr.add(1000);
tr.add(300);
tr.add(500);
tr.add(10);
System.out.println(tr);
}
}
//Even though we inserted 1000 first, TreeSet keeps them sorted.
Output: [10, 300, 500, 1000]
Duplicate Example :
import java.util.TreeSet;
public class Learn {
public static void main(String[] args) {
TreeSet tr = new TreeSet();
tr.add(1000);
tr.add(1000);
tr.add(500);
tr.add(500);
System.out.println(tr);
}
}
//Duplicate values are ignored.
Output : [500, 1000]
Null Example :
import java.util.TreeSet;
public class Learn {
public static void main(String[] args) {
TreeSet tr = new TreeSet();
tr.add(null);
System.out.println(tr);
}
}
//TreeSet does not allow null.
Output : NullPointerException
Important TreeSet Methods:
add():
- To add element/Object.
tr.add(500);
remove():
- To remove element/Object.
tr.remove(500);
contains():
- To check if element/Object exist.
tr.contains(500);
size():
- To find the number of elements/objects.
tr.size();
first():
- To find the smallest element/object.
tr.first();
last():
- To find the largets element/object.
tr.last();
higher():
- To find the next greater element/object.
tr.higher(50);
lower():
- To find the previous element/object.
tr.lower(200);
public class Learn {
public static void main(String[] args) {
TreeSet tr = new TreeSet();
tr.add(500);
tr.add(200);
tr.add(1000);
tr.add(50);
tr.add(10);
System.out.println(tr);
tr.remove(500);
System.out.println(tr);
System.out.println(tr.size());
System.out.println(tr.first());
System.out.println(tr.last());
System.out.println(tr.higher(50));
System.out.println(tr.lower(200));
}
}
Output:
[10, 50, 200, 500, 1000] //add
[10, 50, 200, 1000] //remove element 500
4 //size
10 //first element
1000 //last element
200 //next higher to element 50
50 //next lower to element 200
Top comments (0)