StackTips

Java Collection Complete Tutorial with Examples

In this tutorial we’ll see the core collection interface available in java and their behavior. Examples in each section will show you the implementation and usage of various collection interfaces.

1. Introduction to Java collection API

Java Collections API is a set of interface and implementations included in the java standard library. A collection is a container that holds multiple objects into single unit. Different collection has their own purpose and behaviors. All collection interfaces and classes are available under java.util package.
Collection interfaces are the abstract behavior of each collection.

Java Collection Complete Tutorial and Examples

2. Collection Interface

Collection interface is the root of collection hierarchy and it represents general purpose behavior for the entire interface in this hierarchy. It doesn’t have a concrete implementation.

3. Set Interface

  • A set is a collection that doesn’t allow duplicate entries. A set has the same methods as the collection interface. It can contain at least one 1 null element.
  • The set implementations are HashSet, LinkedHashSet and TreeSet.
  • Element in HashSet, LinkedHashSet are not sorted but TreeSet is sorted.

Example: SetExample.java

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class SetExample {
  public static void main(String args[]) { 
     int count[] = {34, 22,10,60,30,22};
     Set<Integer> set = new HashSet<Integer>();
     try{
        for(int i = 0; i<5; i++){
           set.add(count[i]);
        }
        System.out.println("Initial Set=" + set);        

        set.remove(30);        
        System.out.println("Values after delete=" + set);

        System.out.println("Retrieving Values");        
        Iterator<Integer> iterator = set.iterator();
        while(iterator.hasNext()){
        	System.out.println(iterator.next());
        }     

     }
     catch(Exception e){}
  }
}

Output

Initial Set=[34, 22, 10, 30, 60]
Values after delete=[34, 22, 10, 60]
Retrieving Values
34
22
10
60

4. HashSet

  • HashSet is an abstract implementation of Set interface. It creates a collection that uses a hash table for storing the elements.
  • A HashTable uses hashing mechanism to store the objects. Hashing means, a key is used to determine a unique value, called its hash code. Every hash code represents a data associated with key.

For example, please refer the previous example block

5. LinkedHashSet

  • LinkedHashSet maintains a linked list of the entries in the set.
  • The elements are stored in the order in which they were inserted.
  • While retrieving the LinkedHashSet elements using an Iterator, the elements will be returned in the order in which they were inserted.

Example: LinkedHashSetExample.java

import java.util.Iterator;
import java.util.LinkedHashSet;

public class LinkedHashSetExample {
	public static void main(String args[]) {
		int count[] = { 34, 22, 10, 60, 30, 22, 25 };
		LinkedHashSet<Integer> set = new LinkedHashSet<Integer>();

		try {
			for (int i = 0; i < 7; i++) {
				set.add(count[i]);
			}
			System.out.println("Initial Set=" + set);

			set.remove(30);
			System.out.println("Values after delete=" + set);

			System.out.println("Retrieving Values");
			Iterator<Integer> iterator = set.iterator();
			while (iterator.hasNext()) {
				System.out.println(iterator.next());
			}

		} catch (Exception e) {
		}
	}
}

Output

Initial Set=[34, 22, 10, 60, 30, 25]
Values after delete=[34, 22, 10, 60, 25]
Retrieving Values
34
22
10
60
25

6. TreeSet

TreeSet is a Set implementation that uses tree concept for storing object. It stores the elements in sorted order. Accessing TreeSet is quite faster than other set implementations.

TreeSet Example

Example: TreeSetExample.java

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

public class TreeSetExample {

	public static void main(String args[]) {
		int count[] = { 14, 43, 10, 55, 30, 22,40};
		Set<Integer> set = new TreeSet<Integer>();
		try {
			for (int i = 0; i < 6; i++) {
				set.add(count[i]);
			}
			System.out.println("Intial Set=" + set);

			set.remove(30);
			System.out.println("Values after delete=" + set);

			System.out.println("Retrieving Values");
			Iterator<Integer> iterator = set.iterator();
			while (iterator.hasNext()) {
				System.out.println(iterator.next());
			}

		} catch (Exception e) {
		}
	}
}

Output

Intial Set=[10, 14, 22, 30, 43, 55]
Values after delete=[10, 14, 22, 43, 55]
Retrieving Values
10
14
22
43
55

7. List Interface

  • A List is an ordered collection of elements
  • It may contain duplicate
  • The indexing of the elements is similar to Array. The first index of List is zero.
  • The elements can be manipulated based on their indexed positions
  • Common List implementations are ArrayList and LinkedList

8. ArrayList 

The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed. Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk.

8.1. Loop ArrayList In Java

8.2. Sort an ArrayList in java

9. LinkedList

The LinkedList class extends AbstractSequentialList and implements the List interface. It provides a linked-list data structure.

import java.util.LinkedList;

public class LinkedListExample {
	public static void main(String args[]) {
		// create a linked list
		LinkedList<String> list = new LinkedList<String>();
		list.add("F");
		list.add("E");
		list.add("D");
		list.add("E");
		list.add("C");
		list.addLast("G");
		list.addFirst("B");
		list.add(1, "E1");
		System.out.println("Values of LinkedList=" + list);

		// remove first and last elements
		list.removeFirst();
		list.removeLast();
		System.out.println("After deleting first and last= " + list);

		// remove elements from the linked list
		list.remove("C");
		list.remove(4);
		System.out.println("After Delete" + list);
	}
}

Output

Values of LinkedList=[B, E1, F, E, D, E, C, G]
After deleting first and last= [E1, F, E, D, E, C]
After Delete[E1, F, E, D]

Note: This tutorial is not fully complete. We are continued to write below sections

10. Queue Interface

11. Map Interface

12. Ordering Collection

13. Comparable Interface

14. Comparator Interface

15. References

http://docs.oracle.com/

nilanchala avtar

Nilanchala Panigrahy

A blogger, a bit of tech freak and a software developer. He is a thought leader in the fusion of design and mobile technologies. He is the author of Xamarin Mobile Application Development for Android Book (goo.gl/qUZ0XV3)