Java Collections

Collections in Java

Java collections provides a framework to store a group of objects in a single unit is called collection of the object

As name suggests its group of items into one unit.

Collection framework got introduced in JDK 1.2. It provides many classes and interfaces

  • Classes– ArrayList, Linked List, HashSet, TreeSet, HashMap, TreeMap, Vector
  • Interface-Collection, Iterator, List Iterator, List, Set, Map

A collections framework contains three things

  • Interfaces
  • Implementations
  • Algorithms

Why Collection framework?

  • The main reason is to reduce the programmer effort on creating collection framework rather programmer can concentrate on using the variety of methods available in framework
  • Programmer can use the best use of the framework to increase the speed of the program

Collection Hierarchy

Collection:

All the sub classes in collection family implements Collection interface. It is the foundation of all the interfaces/classes under collection family.

The main methods under collection interface are:

  • int size(); //checks the size of the collection
  • boolean isEmpty( );//checks whether the collection is empty or not
  • boolean contains(Object element); //checks whether it contains any element or not
  • boolean add(Object element);    // adds element into collection
  • boolean remove(Object element);    // removes element from the collection
  • Iterator iterator(); //It provides an iterator to step through the collection

Iterator

It provides the capability to step through the elements into the collection object in forward direction

These are the three main methods provides access to the content of the collection.

  • Object next() // next() method “reads” an element from the collection
  • boolean hasNext() // hasNext() checks whether it has next element while looping through the collection
  • void remove() //remove() removes element from the collection

The below example uses collection add method to add elements into the array list. Also it uses iterator to iterate the collection(Arraylist)

package com.itwhistle.collections;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class ITWhistleCollection {
	public static void main(String[] args) {
		Collection c = new ArrayList();
		for (int i = 1; i <= 10; i++) {
			c.add(i);
		}
		Iterator iter = c.iterator();
		while (iter.hasNext()) {
			System.out.println(iter.next());

		}
	}
}

List Interface:

List interface adds the notion of the order and its the child interface of the Collection.

  • It will have a control of where the element is added in the collection
  • It allows duplicate elements
  • You can List Iterator to step through the elements in the list

ArrayList, LinkedList, Vector and Stack implements List interface.

So to create an instance for List interface we must do like this:

         List listObj1=new ArrayList();
         List listObj2=new LinkedList();
         List listObj3=new Vector();
         List listObj4=new Stack();

ArrayList:

Array List uses dynamic array to store elements hence the size is dynamically increases or decreases. ArrayList is a java class implements List Interface

  • It can have duplicates
  • It is as-synchronous so famously used for multi threading.
  • The elements inside the ArrayList are randomly accessed

The below example adds 1 to 10 Integers(Numbers) into the arraylist. ALso it uses iterator to step/loop through the elements inside the arraylist

package com.itwhistle.collections;

import java.util.*;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class ITWhistleArrayList {
	public static void main(String[] args) {
		
		ArrayList<Integer> list = new ArrayList<Integer>();
		for (int i = 1; i <= 10; i++) {
			list.add(i);
		}
		System.out.println("Printing the size of the IT Whistle List "+list.size());
		Iterator iter = list.iterator();
		while (iter.hasNext()) {
			System.out.println(iter.next());

		}
	}
}

LinkedList:

Linked List maintains the insertion order and hence it is Synchronized. It can also store duplicate elements.

  • Each node stores link to next and previous nodes
  • Low cost insert and delete
  • High Cost random access
  • Sequential access

The below example adds 1 to 10 integers(numbers) into the LinkedList.:

package com.itwhistle.collections;

import java.util.*;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class ITWhistleLinkedList {
	public static void main(String[] args) {
		
		LinkedList<Integer> list = new LinkedList<Integer>();
		for (int i = 1; i <= 10; i++) {
			list.add(i);
		}
		System.out.println("Printing the size of the IT Whistle List "+list.size());
		Iterator iter = list.iterator();
		while (iter.hasNext()) {
			System.out.println(iter.next());

		}
	}
}

Vector:

Vector uses dynamic array to store the elements.

  • It is similar to Array List but synchronized.
  • It can also have additional methods which is not available in Collection framework.

The below example adds 1 to 10 integers(numbers) into the Vector:

package com.itwhistle.collections;

import java.util.*;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class ITWhistleLinkedList {
	public static void main(String[] args) {
		
		Vector<Integer> list = new Vector<Integer>();
		for (int i = 1; i <= 10; i++) {
			list.add(i);
		}
		System.out.println("Size of the IT Whistle Vector List "+list.size());
		Iterator iter = list.iterator();
		while (iter.hasNext()) {
			System.out.println(iter.next());

		}
	}
}

Stack:

Stack is Last in First Out data structure. It contains push(), boolean peek(), boolean push(object o) methods which defines the properties of the Stack

It is child class of Vector

package com.itwhistle.collections;

import java.util.*;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class ITWhistleStack {
	public static void main(String[] args) {
		
		Stack<Integer> list = new Stack<Integer>();
		for (int i = 1; i <= 10; i++) {
			list.add(i);
		}
		System.out.println("Printing the size of the IT Whistle List "+list.size());
		Iterator iter = list.iterator();
		while (iter.hasNext()) {
			System.out.println(iter.next());

		}
	}
}

Set:

Set is an interface extends Collection interface that contains no duplicate elements. At most it can contain one null element.

TreeSet, HashSet, LinkedHashSet implements Set interface.

So to create an instance for Set interface we must do like this:

Set hashSet=new HashSet();
Set linkedHashSet=new LinkedHashSet();
Set treeSet=new TreeSet();

HashSet:

HashSet uses hash table to store elements. It implements Set Interface.

The below example adds (Zebra, Boy, Cat, Apple). When it reads, it does randomly

package com.itwhistle.collections;

import java.util.*;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class ITWhistleHashSet {
	public static void main(String[] args) {
		
		HashSet<String> hashSet = new HashSet<String>();
		hashSet.add("Zebra");
		hashSet.add("Boy");
		hashSet.add("Cat");
		hashSet.add("Apple");
		System.out.println("Printing the size of the IT Whistle List "+hashSet.size());
		Iterator iter = hashSet.iterator();
		while (iter.hasNext()) {
			System.out.println(iter.next());

		}
	}
}

LinkedHashSet:

It extends Hashset and implements Set interface. Like HashSet it also contains unique elements. It maintains the insertion order and allows null elements.

The below example adds (Zebra, Boy, Cat, Apple). When it prints, it puts them in insertion order.

package com.itwhistle.collections;

import java.util.*;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class ITWhistleLinkedHashSet {
	public static void main(String[] args) {
		
		LinkedHashSet<String> linkedHashSet = new LinkedHashSet<String>();
		linkedHashSet.add("Zebra");
		linkedHashSet.add("Boy");
		linkedHashSet.add("Cat");
		linkedHashSet.add("Apple");
		System.out.println("Printing the size of the IT Whistle List "+linkedHashSet.size());
		Iterator iter = linkedHashSet.iterator();
		while (iter.hasNext()) {
			System.out.println(iter.next());

		}
	}
}

SortedSet:

Sortted set introduced into java to set the whole elements into order. SortedSet elements are arranged in ascending order.

It extends AbstractSet, AbstractCollection and implements Set interface

To create an object, you must do like the below:

SortedSet<String> sortSet= new TreeSet<String>();

TreeSet:

TreeSet implements Set interface that uses tree of storage. Similar to HashSet, it contains unique elements.

  • The elements are stored in ascending order
  • Retrieval of elements are faster in Tree Set

The below example adds(Zebra, Boy, Cat, Apple) But it stores them in ascending order hence the output shown below prints in ascending order:

package com.itwhistle.collections;

import java.util.*;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class ITWhistleTreeSet {
	public static void main(String[] args) {

		TreeSet<String> treeSet = new TreeSet<String>();
		treeSet.add("Zebra");
		treeSet.add("Boy");
		treeSet.add("Cat");
		treeSet.add("Apple");
		System.out.println("Printing the size of the IT Whistle Tree Set " + treeSet.size());
		Iterator iter = treeSet.iterator();
		while (iter.hasNext()) {
			System.out.println(iter.next());

		}
	}
}

Map:

Map consists of Key and Value pairs. Each key and value pair is also called as Entry.

  • Map contains Unique keys
  • It allows duplicate values
  • Map cant be traversed so need to covert to Set using entrySet() or keySet()

So to create an instance for Map interface we must do like this:

Map<String,String> hashMap = new HashMap<String, String>();
Map<String,String> treeMap = new TreeMap<String, String>();

<String,String> are type of objects you can have in Map or HashMap or TreeMap

HashMap:

Most commonly used concepts in Map is HashMap. It contains key and value pair.

  • It will not maintain the insertion order
  • HashMap uses concept called Hashing , It is a technique to convert large string into small string so indexing or search operations are faster.
  • It can contain duplicate values but unique keys

The below is the basic example of how HashMap works:

package com.itwhistle.collections;

import java.util.*;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;

public class ITWhistleHashMap {
	public static void main(String[] args) {

		Map<Integer, String> hashMap = new HashMap<Integer, String>();

		hashMap.put(1, "Zebra");
		hashMap.put(2, "Boy");
		hashMap.put(3, "Cat");
		hashMap.put(4, "Apple");
		System.out.println("Printing the size of the IT Whistle Hash Map " + hashMap.size());

		for (Map.Entry<Integer, String> m : hashMap.entrySet())// entrySet() gives you Map.Entry of key and value pair
		{
			System.out.println("Printing key " + m.getKey() + " Value " + m.getValue());
		}
	}
}

SortedMap:

It extends Map interface and it sorts the keys in natural order.

  • TreeMap implements SortedMap interface
  • null key or null value are not permitted in TreeMap

TreeMap:

It implements Map and Navigable interface. It is mainly used to sort the keys in natural order.

In the below example, though the keys are added in different order but it puts them into ascending order(default)

package com.itwhistle.collections;

import java.util.*;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;

public class ITWhistleTreeMap {
	public static void main(String[] args) {

		Map<Integer, String> hashMap = new TreeMap<Integer, String>();

		hashMap.put(4, "Zebra");
		hashMap.put(2, "Boy");
		hashMap.put(3, "Cat");
		hashMap.put(1, "Apple");
		System.out.println("Size of the IT Whistle Hash Map " + hashMap.size());

		for (Map.Entry<Integer, String> m : hashMap.entrySet())// entrySet() gives you Map.Entry of key and value pair
		{
			System.out.println("Printing key " + m.getKey() + " Value " + m.getValue());
		}
	}
}

P.S IT Whistle Java collection page covers the basic hierarchy of collection framework with important java classes with examples required for Java development or automation testing