Collection Interfaces

Java collection interfaces are the base of the Java Collections Framework. In Java, all the collection interfaces are generic(For example: public interface Collection<E>). The syntax <E> is for Generics and when we declare Collection, we should use it to specify the type of Object it can contain. It is use for reducing run-time errors by type-checking the Objects at compile-time. There are many interfaces declared inside the collection package. They are as follows:

  1. Collection Interface
  2. Set Interface
  3. List Interface
  4. Queue Interface
  5. Deque Interface
  6. SortedSet Interface
  7. Map Interface
  8. SortedMap Interface
  9. Iterator Interface
  10. ListIterator Interface

1. Collection Interface

This is the root interface of the collection hierarchy. A collection represents a group of objects known as its elements. Java doesn’t provide any direct implementations for this interface. Below are few methods declared in the collection interface. They are as follows:

Method Role
public boolean add(Object element) Add an element in this collection.
public boolean addAll(Collection c) Add the specified collection elements in the invoking collection.
public boolean remove(Object element) Remove an element from this collection.
public boolean removeAll(Collection c) Remove all the elements of specified collection from the invoking collection.
public boolean retainAll(Collection c) Remove all the elements of invoking collection except the specified collection.
public int size() Return total number of elements in the collection.
public void clear() Remove all element from the collection.
public boolean contains(Object element) Used to search an element.
public boolean containsAll(Collection c) Used to search the specified collection in this collection.
public Iterator iterator() Returns an iterator.
public Object[] toArray() Converts collection into array.
public boolean isEmpty() Check if collection is empty.
public boolean equals(Object element) Compares two collection.
public int hashCode() Returns the hashcode number for collection.

2. Set Interface

Set is a collection that cannot contain duplicate elements. The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited. Below are few methods declared in the set interface. They are as follows:

Method Role
public boolean add() Add an element to the collection.
public void clear() Remove all element from the collection.
public boolean isEmpty() Check if collection is empty.
public boolean contains() Used to search an element.
public Iterator iterator() Returns an iterator.
public int size() Return total number of elements in the collection.
public boolean remove() Remove an element from the collection.

Let us see an example:

package collectionInterfaces;

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

public class SetTest {

  public static void main(String[] args) {
    Set<Integer> set = new HashSet<Integer>();
    int elements[] = {12,23,3,45,66,7,2,88};
    for(int i=0;i<elements.length;i++) {
      set.add(elements[i]);
    }
    System.out.println("Set element(s) -> " +set);
    
    Iterator<Integer> iterator = set.iterator();

    // Traverse set elements
    System.out.println("Traverse set elements: ");
    while(iterator.hasNext()) {
      System.out.println(iterator.next());
    }
    
    TreeSet<Integer> treeSet = new TreeSet<>(set);
    System.out.println("Sorted element(s) -> " +treeSet);
  }
}

Output:

Set element(s) -> [66, 2, 3, 23, 7, 88, 12, 45]
Traverse set elements: 
66
2
3
23
7
88
12
45
Sorted element(s) -> [2, 3, 7, 12, 23, 45, 66, 88]

3. List Interface

List is an ordered collection of objects in which duplicate values can be stored. List Interface is the sub interface of Collection.It holds methods to insert and delete elements in the index basis. Below are few methods declared in the list interface. They are as follows:

Method Role
public void add(int index,Object element) Add an element into the invoking list at the index passed.
public boolean addAll(int index,Collection c) Add all elements of collection c into the invoking list at the index passed.
public object get(int index) Get the object stored at the specified index within the invoking collection.
public object set(int index,Object element) Set an element to the location specified by index within the invoking list.
public object remove(int index) Remove the element at given index from the invoking list and return the deleted element.
public ListIterator listIterator() Return an iterator to the start of the invoking list.
public ListIterator listIterator(int index) Return an iterator to the invoking list that begins at the specified index.

Let us see an example:

package collectionInterfaces;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ListTest {

  public static void main(String[] args) {
    List list = new ArrayList<String>();
    list.add("Huge");
    list.add("Learning");
    list.add("Website");
    System.out.println("List elements -> " + list);
    
    // Remove element from list
    list.remove(0);
    System.out.println("After removing index 1 element the list elements -> " + list);
    
    Iterator iterator = list.iterator();

    // Traverse list elements
    System.out.println("Traverse list elements: ");
    while(iterator.hasNext()) {
      System.out.println(iterator.next());
    }
  }

}

Output:

List elements -> [Huge, Learning, Website]
After removing index 1 element the list elements -> [Learning, Website]
Traverse list elements: 
Learning
Website

4. Queue Interface

Queue is an ordered list of objects which is limited to inserting elements at the end of list and deleting elements from the start of list as it follows FIFO principle. Below are few methods declared in the Queue interface. They are as follows:

Method Role
public boolean add(object) Add the given object into the queue.
public Object remove() Removes the head element from the queue.
public Object poll() Retrieves and removes the head of the queue, or returns null if this queue is empty.
public Object peek() Retrieve the head of queue without removing it. Returns null if queue is empty.
public Object element() It is similar to peek(). If queue is empty it throws NoSuchElementException.

Let us see an example:

package collectionInterfaces;

import java.util.LinkedList;
import java.util.Queue;

public class QueueTest {

  public static void main(String[] args) {
    Queue queue = new LinkedList<>();
    queue.add("test element 1"); 
    queue.add("test element 2"); 
    queue.add("test element 3"); 
    queue.add("test element 4"); 

    System.out.println("Queue elements are " + queue);

    // Peek method returns the head element without removing it from deque
    System.out.println("Peek element -> " + queue.peek());
    System.out.println("After peek queue element(s): " + queue);
    
    // Remove method remove head of the queue.
      String removeElement = (String) queue.remove();
      System.out.println("removed element-" + removeElement);
      System.out.println("After remove deque queue(s): " + queue);
  }
}

Output:

Queue elements are [test element 1, test element 2, test element 3, test element 4]
Peek element -> test element 1
After peek queue element(s): [test element 1, test element 2, test element 3, test element 4]
removed element-test element 1
After remove deque queue(s): [test element 2, test element 3, test element 4]

5. Deque Interface

The Deque is belong to the double-ended queue that supports addition or removal of elements from either of any end of the deque, we can use it as a queue (first-in-first-out/FIFO) or as a stack (last-in-first-out/LIFO). Below are few methods declared in the Deque interface. They are as follows:

Method Role
public boolean add(element) Add the given element into the tail.
public void addFirst(element) Add the given element into the head.
public void addLast(element) Add the given element into the tail.
public boolean offer(element) Adds an element to the tail and returns a boolean to define if the insertion was successful.
public boolean offerFirst(element) Adds an element to the head and returns a boolean to define if the insertion was successful.
public boolean offerLast(element)  Adds an element to the tail and returns a boolean to define if the insertion was successful.
public Iterator iterator() Returns an iterator.
public Iterator descendingIterator() Returns an iterator that has the reverse order for this deque.
public void push(element)  Adds an element to the head.
public E pop(element) Removes an element from the head and returns it.
public E removeFirst()  Removes the element at the head.
public E removeLast() Removes the element at the tail.

Let us see an example:

package collectionFramework;

import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedList;

public class DequeTest {

  public static void main(String[] args) {
    Deque deque = new LinkedList<>();
    deque.add("test element 1"); // Add element at tail
    deque.addFirst("test element 2"); // Add element at head
    deque.addLast("test element 3"); // Add element at tail
    deque.push("test element 4"); // Add element at head
    deque.offer("test element 5"); // Add element at tail
    deque.offerFirst("test element 6"); // Add element at head
    deque.offerLast("test element 7");	// Add element at tail

    // Traverse in forward direction
    Iterator iterator = deque.iterator();
    System.out.println("Traverse in forward direction");
    while (iterator.hasNext())
      System.out.println(iterator.next());

    // Traverse in reverse direction
    Iterator reverse = deque.descendingIterator();
    System.out.println("Traverse in reverse direction");
    while (reverse.hasNext())
      System.out.println(reverse.next());

  }
}

Output:

Traverse in forward direction
test element 6
test element 4
test element 2
test element 1
test element 3
test element 5
test element 7
Traverse in reverse direction
test element 7
test element 5
test element 3
test element 1
test element 2
test element 4
test element 6

6. SortedSet Interface

The SortedSet interface extends Set and added values in the set which are sorted in an ascending order. Below are few methods declared in the SortedSet interface. They are as follows:

Method Role
public Comparator comparator( ) Returns the given sorted set’s comparator. If the natural ordering is used for this set, null is returned.
public Object first() Returns the first element in the invoking sorted set.
public SortedSet headSet(Object end) Returns a set whose elements are strictly less than end.
public Object last() Returns the last element in the given sorted set.
public SortedSet subSet(Object start, Object end) Returns a set that includes those elements between start and end.
public SortedSet tailSet(Object tailElement)  Returns a set whose elements are greater than or equal to tailElement.

Let us see an example:

package collectionFramework;

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

public class SortedSetTest {

  public static void main(String[] args) {
    SortedSet<String> sortedSet = new TreeSet<>();
    sortedSet.add("Huge");
    sortedSet.add("Learning");
    sortedSet.add("Website");

    Iterator<String> iterator = sortedSet.iterator();

    // Traverse contents
    System.out.println("Traverse contents: ");
    while(iterator.hasNext()) {
      System.out.println(iterator.next());
    }
  }
}

Output:

Traverse contents: 
Huge
Learning
Website

7. Map Interface

A map contains values on the basis of key i.e. key and value pair. Each key and value pair is known as an entry. Map maps unique keys to values.Map is useful in case of search, update or delete elements on the basis of key. Below are few methods declared in the Map interface. They are as follows:

Method Role
public Object put(Object key, Object value) Insert a value in the map.
public void putAll(Map map) Insert the given map in the map.
public Object remove(Object key) Remove an element for the specified key.
public Object get(Object key) Return the value for the specified key.
public boolean containsKey(Object key) Search the specified key from the map.
public Set keySet()  Return the Set view containing all the keys.
public Set entrySet() Return the Set view containing all the keys and values.
public int size() Return total number of key/value pair in the map.
public boolean isEmpty()  Check if map is empty.

Let us see an example:

package collectionFramework;

import java.util.HashMap;
import java.util.Map;

public class MapTest {

  public static void main(String[] args) {
    Map<Integer, String> map = new HashMap<Integer, String>();
    map.put(1, "Ankit");
    map.put(2, "Ishwar");
    map.put(3, "Arjun");
    
    for(Map.Entry me:map.entrySet()) {
      System.out.println("Key -> " + me.getKey()+" Value -> " + me.getValue());
    }
  }

}

Output:

Key -> 1 Value -> Ankit
Key -> 2 Value -> Ishwar
Key -> 3 Value -> Arjun

8. SortedMap Interface

The SortedMap interface extends Map interface. It ensures that the entries are maintained in an ascending key order. Also we can traverse the SortedMap elements in sorted order of keys. Below are few methods declared in the SortedMap interface. They are as follows:

Method Role
public Comparator comparator() Returns the given sorted map’s comparator. If the natural ordering is used for this map, null is returned.
public Object firstKey() Returns the first key in the given map.
public Object lastKey() Returns the last element in the given map.
public SortedMap subMap(Object start, Object end) Returns a map that includes those elements between start and end.
public SortedMap tailMap(Object tailElement) Returns a map whose elements are greater than or equal to tailElement.

Let us see an example:

package collectionFramework;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

public class SortedMapTest {
  public static void main(String[] args) {
    SortedMap<Integer, String> sortedMap = new TreeMap<Integer, String>();
    sortedMap.put(new Integer(1), "Huge");
    sortedMap.put(new Integer(2), "Learning");
    sortedMap.put(new Integer(3), "Website");

    Set set = sortedMap.entrySet();

    Iterator iterator = set.iterator();

    // Traverse map elements
    while(iterator.hasNext()) {
      Map.Entry mapEntry = (Map.Entry) iterator.next();
      int key = (Integer) mapEntry.getKey();
      String value = (String) mapEntry.getValue();

      System.out.println("Key -> " + key + "  Value -> " + value);
    }
  }
}

Output:

Key -> 1  Value -> Huge
Key -> 2  Value -> Learning
Key -> 3  Value -> Website

9. Iterator Interface

It is an interface or universal iterator which can apply any of the collection object. Wit the help of iterator, we can perform both read and remove operations. It is a revised version of Enumeration with additional functionality of remove-ability of a element. Below are few methods declared in the Iterator interface. They are as follows:

Method Role
public boolean hasNext() Returns true if there are more elements. Otherwise it returns false.
public Object next() Returns the next element. If there is no next element then it throws NoSuchElementException.
public void remove() Removes the current element.

Let us see an example:

package collectionFramework;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class IteratorTest {

  public static void main(String[] args) {

    List<String> roommates = new LinkedList<>();
    roommates.add("Dam");
    roommates.add("Ajay");
    roommates.add("Akhilesh");
    roommates.add("Himanshu");

    Iterator<String> iterator = roommates.listIterator();

    // Traverse names
    System.out.println("Names in forward direction: ");
    while(iterator.hasNext()) {
      System.out.println(iterator.next());
    }
  }
}

Output:

Names in forward direction: 
Dam
Ajay
Akhilesh
Himanshu

Limitations of Iterator :

  • Only forward direction iteration is possible.
  • Iterator does not support replacement and addition of new element.

10. ListIterator Interface

ListIterator is only applicable for List collection implemented classes like arraylist, linkedlist etc. It provides the bi-directional iteration. ListIterator must be used when we want to enumerate elements of List. ListIterator has more methods or features than iterator. Below are few methods declared in the Iterator interface. They are as follows:

Method Role
public void add(E e) Add the specified element into the list.
public boolean hasNext() Returns true if there are more elements in the list iterator in the forward direction. Otherwise it returns false.
public boolean hasPrevious() Returns true if there are more elements in the list iterator in the reverse direction. Otherwise it returns false.
public E next() Returns the next element and moves the cursor position next.
public int nextIndex() Returns the index of the element that would be returned by a subsequent call to next().
public E previous() Returns the previous element in the list and moves the cursor position reverse.
public int previousIndex() Returns the index of the element that would be returned by a subsequent call to previous().
public void remove() Removes the last one element that was returned by next() or previous().

Let us see an example:

package collectionFramework;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

public class ListIteratorTest {

public static void main(String[] args) {

List roommates = new LinkedList<>();
roommates.add("Dam");
roommates.add("Ajay");
roommates.add("Akhilesh");
roommates.add("Himanshu");

ListIterator listIterator = roommates.listIterator();

// Traverse names in forward direction
System.out.println("Names in forward direction: ");
while(listIterator.hasNext()) {
System.out.println(listIterator.next());
}

// Traverse names in reverse direction
System.out.println("Names in reverse direction: ");
while(listIterator.hasPrevious()) {
System.out.println(listIterator.previous());
}
}
}



Output:

Names in forward direction:
Dam
Ajay
Akhilesh
Himanshu
Names in reverse direction:
Himanshu
Akhilesh
Ajay
Dam