Preview:
import java.util.*;
public class TreeSetDemo
{ 
 class MyComparator implements Comparator<String>
{ public int compare(String s1, String s2)
{ if(s1.compareTo(s2)<0) 
return -1;
 if(s1.compareTo(s2)>0) 
 return +1;
 return 0;
}
}
public static void main(String[] args)
{
TreeSet<String> ts = 
 new TreeSet<>(new TreeSetDemo().new MyComparator());
ts.add("hello"); ts.add("world"); ts.add("version");
ts.add("main"); ts.add("method");
System.out.println("Contents: " + ts);
System.out.println();
System.out.println("Higher than \"main\": " + ts.higher("main"));
System.out.println("Lower than \"main\": " + ts.lower("main"));
System.out.println();
SortedSet s = ts.tailSet("method");
System.out.println("TailSet from \"method\": " + s);
s = ts.headSet("method");
System.out.println("HeadSet from \"method\": " + s);
System.out.println();
Iterator it = ts.iterator();
System.out.print("Iteration: ");
while(it.hasNext())
System.out.print(it.next()+" ");
System.out.println();
System.out.println();
Iterator it2 = ts.descendingIterator();
System.out.print("Iteration Descending: ");
while(it2.hasNext())
System.out.print(it2.next()+" ");
System.out.println();
System.out.println("First one: " + ts.pollFirst());
System.out.println("Last one: " + ts.pollLast());
System.out.println("Contents: " + ts);
}
}
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter