Home  >  Core Java

java.util.TreeSet Example in Java

By Arvind Rai, 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())
 
TreeSetDemo.java
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;
    }
}
 
Output:
A
B
C
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us