Wednesday, March 05, 2014

Tree, Set and Map in Java Collection

Java collection API is a set of classes and interface which is used to store multiple objects.There are different type of classes that stores multiple results, in this exercise we will see Tree,Set and Map in Java class through a simple example.

package helloworld;

import java.util.*;

public class CollectionsTest {
public CollectionsTest() {
super();
}

public static void main(String[] args) {

List l = new ArrayList();
Set s = new TreeSet();
Map m = new TreeMap();

l.add(new Integer(1));
l.add(new Integer(4));
l.add(new Integer(3));
l.add(new Integer(2));
l.add(new Integer(3));
System.out.println(l);

Iterator i =l.iterator();

while(i.hasNext()){
System.out.println("Values: "+i.next());
}

s.add(new Integer(1));
s.add(new Integer(4));
s.add(new Integer(3));
s.add(new Integer(2));
s.add(new Integer(3));
System.out.println(s);
i=s.iterator();
while(i.hasNext()){
System.out.println("Values: "+i.next());
}

m.put(new Integer(1),"A");
m.put(new Integer(4),"B");
m.put(new Integer(3),"C");
m.put(new Integer(2),"D");
m.put(new Integer(3),"E");
m.put(new Integer(3),"F");
System.out.println(m);

i=m.entrySet().iterator();
while(i.hasNext()){
System.out.println("Values: "+i.next());
}

}
}


If you will execute this code you will get following result


[1, 4, 3, 2, 3]
Values: 1
Values: 4
Values: 3
Values: 2
Values: 3
[1, 2, 3, 4]
Values: 1
Values: 2
Values: 3
Values: 4
{1=A, 2=D, 3=F, 4=B}
Values: 1=A
Values: 2=D
Values: 3=F
Values: 4=B

Now lets analyse the result

For the list the result is same as the data that we have entered --> so we can define List as a class which stores all the data in a particular order and does not check for duplication of records.


For the Set result you can observe that the duplicate records are removed and it has displayed only the unique values. So set is again a class which stores multiple data and avoid duplication of records

Thirdly we have the map result which again shows that there is no duplication of record and if there are multiple record with the same key the last updated value is taken so in this example for key 3 there are three values C,E and F however when we displayed the result the last value was taken.

Further list and set uses the same method to add element that is add() however map uses put() method to insert data.

One more important point is that list and set extends Iterable interface indirectly hence can directly create an iterator object for list and set however in case of a map it has to go via entrySet() to get access to the Iterator.

No comments: