In our earlier tutorials we have seen about LinkedHashMap and LinkedHashSet with simple examples. Now lets see about TreeSet and its difference between HashSet and also how its works. First lets discuss about the main properties of TreeSet class.
Now lets see simple example code which shows how it use TreeSet.
OUTPUT:
- TreeSet always holds unique values as same as HashSet.
- TreeSet implements NavigableSet interface which extends the SortedSet interface.
- Values stored in TreeSet will be in ascending order by default, hence its won't maintain insertion order as like LinkedHashSet.
- If we need to order the values in descending order then we need to use Collections.reverseOrder() as like in below example.
Now lets see simple example code which shows how it use TreeSet.
import java.util.Collections;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
public class TreeSetTest {
public static void main(String[] args) {
// By default value will be sorted in ascending order
Set<String> tsAsc = new TreeSet<String>();
// To sort values in descending order
Set<String> tsDesc = new TreeSet<String>(Collections.reverseOrder());
tsAsc.add("Daniel");
tsAsc.add("Chris");
tsAsc.add("Amit");
tsAsc.add("Bob");
tsDesc.add("Daniel");
tsDesc.add("Chris");
tsDesc.add("Amit");
tsDesc.add("Bob");
// Printing TreeSet values in Ascending order .
System.out.println("TreeSet values in Ascending order :::::::::::::::");
Iterator<String> itr1 = tsAsc.iterator();
while(itr1.hasNext()){
System.out.println(itr1.next());
}
// Printing TreeSet values in Descending order .
System.out.println("TreeSet values in Descending order :::::::::::::::");
Iterator<String> itr2 = tsDesc.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
}
}
}
OUTPUT:
TreeSet values in Ascending order :::::::::::::::
Amit
Bob
Chris
Daniel
TreeSet values in Descending order :::::::::::::::
Daniel
Chris
Bob
Amit
No comments:
Write comments