java.util.TreeSet Example in Java
August 27, 2013
java.util.TreeSet implements SortedSet. TreeSet keeps natural ordering of elements and can do ordering on the basis of any given Comparator depending on the constructor used while creating the object of TreeSet. In our example we have used a TreeSet which will do ordering according to given comparator. by default treeSet is synchronized. We can synchronize it by
SortedSet s = Collections.synchronizedSortedSet(new TreeSet())
package com.concretepage.util; import java.util.Comparator; import java.util.SortedSet; import java.util.TreeSet; public class TreeSetDemo { public static void main(String[] args) { SortedSet<Bean> set = new TreeSet<Bean>(new A()); set.add(new Bean("A")); set.add(new Bean("C")); set.add(new Bean("B")); for(Bean ob : set){ System.out.println(ob.name); } } } class A implements Comparator<Bean> { @Override public int compare(Bean b1, Bean b2) { return b1.name.compareTo(b2.name); } } class Bean { public String name; public Bean(String name) { this.name = name; } }
A B C