Saturday, 9 May 2015

TreeSet in Java Collection With Very Basic Example

What is TreeSet in java collection

Before going deep in TreeSet please give 2 minutes for getting
introduction of Set interface .

The Java platform contains three general 

purpose Set implementations: HashSetTreeSet, and LinkedHashSetHashSet, which stores its elements in a hash table, is the best-performing implementation; however it makes no guarantees concerning the order of iteration. TreeSet, which stores its elements in a red-black tree, orders its elements based on their values; it is substantially slower than HashSetLinkedHashSet, which is implemented as a hash table with a linked list running through it, orders its elements based on the order in which they were inserted into the set (insertion-order). 

java.util.TreeSet<E> extends java.util.AbstractSet<E> class. It implements Serializable, Set, SortedSet interface. TreeSet is also representation mathematical  Set. But TreeSet store elements in ordered way. Whenever we want to store objects in set in ordered way we use TreeSet.


Use Of TreeSet

1. Its contains unique values.
2. It store objects in ordered way.
3. Access and retrieval times are quite fast.

Example :

In this example we will see how TreeSet manage order. For Integer, String, Double Tree set store in ascending order.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.javasuitor.demo;

import java.util.Iterator;
import java.util.TreeSet;

/**
 * @author Ashok
 * 
 */
public class TreeSetDemo {
 public static void main(String[] args) {
  TreeSet<Integer> numberSet = new TreeSet<Integer>();

  numberSet.add(10);
  numberSet.add(4);
  numberSet.add(2);
  numberSet.add(9);
  numberSet.add(8);
  numberSet.add(3);
  numberSet.add(7);
  numberSet.add(6);
  numberSet.add(5);
  numberSet.add(1);

  // Traverse TreeSet
  System.out.println("Elements in TreeSet");
  for (Integer i : numberSet) {
   System.out.println(i);
  }

  // Another way to traverse TreeSet
  System.out.println("Traverse by Iterator");
  Iterator<Integer> iterator = numberSet.iterator();
  while (iterator.hasNext()) {
   System.out.println(iterator.next());
  }

 }

}


OUTPUT :

Elements in TreeSet
1
2
3
4
5
6
7
8
9
10
Traverse by Iterator
1
2
3
4
5
6
7
8
9
10


You can see in output all numbers are arranged in ascending order. I hope you understood the basic functionality of TreeSet.

In next blog I will dive u deep into TreeSet. Don't worry its does require additional oxygen supply :)


Please feel free to ask any question.


Happy learning. 

No comments:

Post a Comment