Add elements to a TreeSet
boolean add(E e)
- Adds the specified element to this set if it is not already present.
boolean addAll(Collection<? extends E> c)
- Adds all of the elements in the specified collection to this set.
import java.util.TreeSet;
public class Main {
public static void main(String args[]) {
TreeSet<String> ts = new TreeSet<String>();
ts.add("C");
ts.add("A");
ts.add("B");
ts.add("E");
ts.add("F");
ts.add("java2s.com");
System.out.println(ts);
}
}
The output:
[A, B, C, E, F, java2s.com]
import java.util.Arrays;
import java.util.TreeSet;
public class Main {
public static void main(String args[]) throws Exception {
String elements[] = { "java2s.com", "C", "D", "G", "F" };
TreeSet<String> set = new TreeSet<String>(Arrays.asList(elements));
System.out.println(set.headSet("D"));
System.out.println(set.tailSet(""));
}
}
The output:
[C]
[C, D, F, G, java2s.com]
import java.util.Comparator;
import java.util.TreeSet;
class MyComparator implements Comparator<String> {
public int compare(String a, String b) {
String aStr, bStr;
aStr = a;
bStr = b;
return bStr.compareTo(aStr);
}
}
public class Main{
public static void main(String args[]) {
TreeSet<String> ts = new TreeSet<String>(new MyComparator());
ts.add("java2s.com");
ts.add("A");
ts.add("B");
ts.add("E");
ts.add("F");
ts.add("D");
for (String element : ts)
System.out.print(element + " ");
System.out.println();
}
}
The output:
java2s.com F E D B A
import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;
public class Main {
public static void main(String args[]) throws Exception {
String elements[] = { "java2s.com", "C", "D", "G", "F" };
Set<String> set = new TreeSet<String>(Collections.reverseOrder());
for (int i = 0, n = elements.length; i < n; i++) {
set.add(elements[i]);
}
System.out.println(set);
}
}
The output:
[java2s.com, G, F, D, C]