tree set java code example
Example 1: TreeSet in java
// java treeset example
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetExamples
{
public static void main(String[] args)
{
TreeSet ts = new TreeSet();
ts.add("red");
ts.add("blue");
ts.add("green");
ts.add("red");
Iterator iterate = ts.iterator();
while(iterate.hasNext())
{
System.out.println(iterate.next());
}
}
}
Example 2: java treeset
import java.util.*;
// Declare the variable using the interface of the object for flexibility.
// Non-primative data types only.
Set movies = new TreeSet();
movies.add(E);
// TreeSet will be sorted by element.
// Work with any comparable object.
movies.add("The Shining");
movies.add("Dawn of the Dead");
movies.add("Zombieland");
Example 3: TreeSet
// par défaut
TreeSet ensemble = new TreeSet();
// comparateur
Comparator comparateur = new Comparateur();
TreeSet ensemble = new TreeSet(comparateur);
// classe Comparateur implémentant l'interface Comparator
public class Comparateur implements Comparator {
public int compare(Object obj1, Object obj2){
return ((Comparable)obj2).compareTo(obj1);
}
public boolean equals(Object obj){
return this.equals(obj);
}
}
Example 4: what is treeset in java
- TreeSet sorts the order and don't accept null
Example 5: treeset
TreeSet: Can contain only unique values and it is sorted in ascending order
TreeMap: Can contain only unique keys and keys are sorted in ascending order.