A simple TreeSet example

The following is a very simple TreeSet example. From this simple example, you will see:

  • TreeSet is sorted
  • How to iterate a TreeSet
  • How to check empty
  • How to retrieve first/last element
  • How to remove an element

If you want to know more about Java Collection, check out the Java Collection hierarchy diagram.

import java.util.Iterator;
import java.util.TreeSet;
 
public class TreeSetExample {
 
   public static void main(String[] args) {
	System.out.println("Tree Set Example!\n");
	TreeSet<Integer> tree = new TreeSet<Integer>();
	tree.add(12);
	tree.add(63);
	tree.add(34);
	tree.add(45);
 
	// here it test it's sorted, 63 is the last element. see output below
	Iterator<Integer> iterator = tree.iterator();
	System.out.print("Tree set data: ");
 
	// Displaying the Tree set data
	while (iterator.hasNext()) {
		System.out.print(iterator.next() + " ");
	}
	System.out.println();
 
	// Check empty or not
	if (tree.isEmpty()) {
		System.out.print("Tree Set is empty.");
	} else {
		System.out.println("Tree Set size: " + tree.size());
	}
 
	// Retrieve first data from tree set
	System.out.println("First data: " + tree.first());
 
	// Retrieve last data from tree set
	System.out.println("Last data: " + tree.last());
 
	if (tree.remove(45)) { // remove element by value
		System.out.println("Data is removed from tree set");
	} else {
		System.out.println("Data doesn't exist!");
	}
	System.out.print("Now the tree set contain: ");
	iterator = tree.iterator();
 
	// Displaying the Tree set data
	while (iterator.hasNext()) {
		System.out.print(iterator.next() + " ");
	}
	System.out.println();
	System.out.println("Now the size of tree set: " + tree.size());
 
	// Remove all
	tree.clear();
	if (tree.isEmpty()) {
		System.out.print("Tree Set is empty.");
	} else {
		System.out.println("Tree Set size: " + tree.size());
	}
   }
}

Output:

Tree Set Example!

Tree set data: 12 34 45 63
Tree Set size: 4

First data: 12
Last data: 63

Data is removed from tree set

Now the tree set contain: 12 34 63
Now the size of tree set: 3

Tree Set is empty.
Category >> Collections  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>

  1. M A Hossan on 2012-6-15

    This is a very good example of tree set could you answer of my one question Place I am learning java how the elements is stored in a tree set ,hashset,treemap and hashmap.if you know the Answer place send it to my email address .thank you very much

  2. Admin on 2012-6-17

    you can read this post about differences among those classes.
    http://www.programcreek.com/2009/02/the-interface-and-class-hierarchy-for-collections/

  3. 한병호 on 2013-11-24

    ——————————————————————
    class player implements Comparable{

    String name;

    int shot_percentage;

    int height;

    //// ??? help!!

    @Override

    public int compareTo(player other){

    if(this.shot_percentage > other.shot_percentage)

    return 1;

    else{

    if(this.height > other.height)

    return 1;

    else return -1;

    }

    }

    }
    —————————————————————-
    *****compareTo – I don’t know how make it? can you give some help?

    It don’t work as I think…

    ————————————————————————-
    package basketball;

    import java.io.*;

    import java.util.*;

    class player implements Comparable{

    String name;

    int shot_percentage;

    int height;

    @Override

    public int compareTo(player other){

    if(this.shot_percentage > other.shot_percentage)

    return 1;

    else{

    if(this.height > other.height)

    return 1;

    else return -1;

    }

    }

    }

    public class bball {

    static final int bufferlen = 999999;

    public static void main(String[] args) {

    // TODO Auto-generated method stub

    int data =0;

    byte[] b = new byte[bufferlen];

    try {

    FileInputStream fin = new FileInputStream(args[0]);

    BufferedInputStream din = new BufferedInputStream(fin);

    din.read(b);

    String s = new String(b,0,b.length);

    StringTokenizer st = new StringTokenizer(s);

    String tc = st.nextToken();

    for(int i=0;i<Integer.parseInt(tc);i++){

    int draft_number; // 낮을 수록 잘하는 선수 lowest 선수가 제일 많이,키가 큼.

    String n; // 각 학교의 n 학생

    String m; // m 분 동

    String p; // 각 팀의 뛰는 플레이어 p

    n = st.nextToken();

    m = st.nextToken();

    p = st.nextToken();

    TreeSet team = new TreeSet();

    //Iterator draft = team.iterator();

    for(int j=0;j<Integer.parseInt(n);j++){

    String name,shot_percentage,height;

    name = st.nextToken();

    shot_percentage = st.nextToken();

    height = st.nextToken();

    player pl = new player();

    pl.name = name;

    pl.shot_percentage = Integer.parseInt(shot_percentage);

    pl.height = Integer.parseInt(height);

    //TreeSet team = new TreeSet();

    team.add(pl);

    //Iterator draft = team.iterator();

    //System.out.println(team);

    }

    System.out.println(“—–“);

    Iterator draft = team.iterator();

    while(draft.hasNext()){

    player ply = draft.next();

    System.out.println(ply.name+” “+ply.shot_percentage);

    }

    System.out.println(“—–“);

    }

    din.close();

    fin.close();

    }catch(IOException e){

    System.out.println(“입출력에 오류가 있네요…!”);

    }

    }

    }

  4. 한병호 on 2013-11-24

    sorry… my mistake….

    ———————————

    @Override

    public int compareTo(player other){

    int i;

    if(this.shot_percentage == other.shot_percentage){

    if(this.height == other.height) return 0;

    else return this.height > other.height? 1:-1;

    }else return this.shot_percentage > other.shot_percentage? 1:-1;

    }

  5. Alonso Isidoro Roman on 2014-8-13

    Thank you very much, you saved my day!

  6. Shivam Singh on 2015-11-19

    Well explain examples and visit more example of TreeSet Examples

Leave a comment

*