TreeSet クラス

import java.io.*;
import java.util.*;

class Comp implements Comparator <String> {
	public int compare (String k1,  String k2)
	{
		return -k1.compareTo(k2);
	}
}

public class Test {

	public static void main(String args[]) throws IOException
	{
		int i1, sw;

		System.out.println("TreeSetオブジェクト a を生成");
		TreeSet <String> a = new TreeSet <String> ();
		a.add("mno");
		System.out.println("   mno を追加");
		a.add("JKL");
		System.out.println("   JKL を追加");
		a.add("ghi");
		System.out.println("   ghi を追加");
		a.add("DEF");
		System.out.println("   DEF を追加");
		a.add("abc");
		System.out.println("   abc を追加");
		System.out.print("   結果は");
		Iterator it = a.iterator();
		while (it.hasNext())
			System.out.print(" " + it.next());
		System.out.println();

		System.out.println("a における \"abc\" の headSet と tailSet");
		SortedSet st = a.headSet("abc");
		System.out.println("   headSet (first) " + st.first() + " (last) " + st.last());
		st = a.tailSet("abc");
		System.out.println("   tailSet (first) " + st.first() + " (last) " + st.last());

		System.out.println("要素の削除");
		System.out.print("   要素 \"abc\" の削除");
		a.remove("abc");
		it = a.iterator();
		while (it.hasNext())
			System.out.print(" " + it.next());
		System.out.println();
		System.out.print("   一つおきに削除");
		it = a.iterator();
		sw = 1;
		while (it.hasNext()) {
			it.next();
			if (sw > 0)
				it.remove();
			sw *= (-1);
		}
		it = a.iterator();
		while (it.hasNext())
			System.out.print(" " + it.next());
		System.out.println();

		System.out.println("コンパレータを使用する場合(降順)");
		Comparator<String> cp = new Comp();
		TreeSet <String> b = new TreeSet <String> (cp);
		b.add("mno");
		System.out.println("   mno を追加");
		b.add("JKL");
		System.out.println("   JKL を追加");
		b.add("ghi");
		System.out.println("   ghi を追加");
		b.add("DEF");
		System.out.println("   DEF を追加");
		b.add("abc");
		System.out.println("   abc を追加");
		System.out.print("   結果は");
		it = b.iterator();
		while (it.hasNext())
			System.out.print(" " + it.next());
		System.out.println();
	}
}
		
(出力)
TreeSetオブジェクト a を生成
   mno を追加
   JKL を追加
   ghi を追加
   DEF を追加
   abc を追加
   結果は DEF JKL abc ghi mno
a における "abc" の headSet と tailSet
   headSet (first) DEF (last) JKL
   tailSet (first) abc (last) mno
要素の削除
   要素 "abc" の削除 DEF JKL ghi mno
   一つおきに削除 JKL mno
コンパレータを使用する場合(降順)
   mno を追加
   JKL を追加
   ghi を追加
   DEF を追加
   abc を追加
   結果は mno ghi abc JKL DEF