Collections Framework – The Collection Interface


Collection Interface is a root interface in the collection hierarchy. A Collection represents a group of objects known as its elements. List, Queue and Set are all subinterfaces of Collection interface. JDK does not provide any direct implementations of this interface. But, JDK provides direct implementations of it’s sub-interfaces.

Collection Interface Class Diagram

Here is the class diagram of the Collection interface.
From above class diagram, the Collection interface extends the Iterable interface which is a member of the java.lang package.  Implementing the Iterable interface allows an object to be the target of the "for-each loop" statement.

Collection Interface Simple Example

Let's say Collection of animals, which may be a List, a Set, or another kind of Collection. This idiom creates a new ArrayList (an implementation of the List interface), initially containing all the elements in the animal's list.
import java.util.ArrayList;
import java.util.Collection;

public class CreateCollectionInterfaceExample {

    public static void main(String[] args) {
        // Creating an ArrayList of String using 
     Collection<String> animals = new ArrayList<>();
        // Adding new elements to the ArrayList
        animals.add("Lion");
        animals.add("Tiger");
        animals.add("Cat");
        animals.add("Dog");
        System.out.println(animals);
        
        String[] arrayOfAnimals = new String[4];
        System.out.println(arrayOfAnimals.length);
        arrayOfAnimals[0] = "Lion";
        arrayOfAnimals[1] = "Tiger";
        arrayOfAnimals[2] = "Cat";
        arrayOfAnimals[3] = "Dog";
        for (String string : arrayOfAnimals) {
            System.out.println(string);
        }        
    }
}

Collection Interface Methods/APIs

  • boolean add(E e) - Ensures that this collection contains the specified element (optional operation).
  • boolean addAll(Collection<? extends E> c) - Adds all of the elements in the specified collection to this collection (optional operation).
  • void clear()- Removes all of the elements from this collection (optional operation).
  • boolean contains(Object o) - Returns true if this collection contains the specified element.
  • boolean containsAll(Collection<?> c) - Returns true if this collection contains all of the elements in the specified collection.
  • boolean equals(Object o)- Compares the specified object with this collection for equality.
  • int hashCode() - Returns the hash code value for this collection.
  • boolean isEmpty() - Returns true if this collection contains no elements.
  • Iterator iterator() - Returns an iterator over the elements in this collection.
  • default Stream parallelStream() - Returns a possibly parallel Stream with this collection as its source.
  • boolean remove(Object o)-  Removes a single instance of the specified element from this collection, if it is present (optional operation).
  • boolean removeAll(Collection<?> c) - Removes all of this collection's elements that are also contained in the specified collection (optional operation).
  • default boolean removeIf(Predicate<? super E> filter) - Removes all of the elements of this collection that satisfy the given predicate.
  • boolean retainAll(Collection<?> c) - Retains only the elements in this collection that are contained in the specified collection (optional operation).
  • int size() - Returns the number of elements in this collection.
  • default Spliterator spliterator() - Creates a Spliterator over the elements in this collection.
  • default Stream stream() - Returns a sequential Stream with this collection as its source.
  • Object[] toArray() - Returns an array containing all of the elements in this collection.
  • T[] toArray(T[] a) - Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array.

More Examples

Following is an example to explain a few methods from various class implementations of the above collection methods −
package com.javaguides.javafx.examples;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class CollectionsDemo {

    public static void main(String[] args) {
        // ArrayList
        List < String > list = new ArrayList < > ();
        list.add("element 1");
        list.add("element 2");
        list.add("element 3");
        list.add("element 4");
        System.out.println(" ArrayList Elements");
        System.out.print("\t" + list);

        // LinkedList
        List < String > linkedList = new LinkedList < > ();
        linkedList.add("element 1");
        linkedList.add("element 2");
        linkedList.add("element 3");
        linkedList.add("element 4");
        System.out.println();
        System.out.println(" LinkedList Elements");
        System.out.print("\t" + linkedList);

        // HashSet
        Set < String > set = new HashSet < > ();
        set.add("element 1");
        set.add("element 2");
        set.add("element 3");
        set.add("element 4");
        System.out.println();
        System.out.println(" Set Elements");
        System.out.print("\t" + set);

        // HashMap
        Map < String, String > map = new HashMap < > ();
        map.put("key1", "value1");
        map.put("key2", "value2");
        map.put("key3", "value3");
        map.put("key4", "value4");

        System.out.println();
        System.out.println(" Map Elements");
        System.out.print("\t" + map);
    }
}
Output:
 ArrayList Elements
 [element 1, element 2, element 3, element 4]
 LinkedList Elements
 [element 1, element 2, element 3, element 4]
 Set Elements
 [element 4, element 3, element 2, element 1]
 Map Elements
 {key1=value1, key2=value2, key3=value3, key4=value4}
In JDK 8 and later, the Collection interface also exposes methods Stream stream() and Stream parallelStream(), for obtaining sequential or parallel streams from the underlying collection. (See the lesson entitled Aggregate Operations for more information about using streams.)
This is demonstrated in the below posts:

Comments

Post a Comment