Open In App

Collection Interface in Java

Last Updated : 20 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

The Collection interface in Java is a core member of the Java Collections Framework located in the java.util package. It is one of the root interfaces of the Java Collection Hierarchy. The Collection interface is not directly implemented by any class. Instead, it is implemented indirectly through its sub-interfaces like List, Queue, and Set

For Example, the ArrayList class implements the List interface, a sub-interface of the Collection interface.

Example:

// Using the Collection interface with an ArrayList
import java.util.*;

public class Geeks {
    public static void main(String[] args) {
      
        // Create a Collection using ArrayList
        Collection<String> c = new ArrayList<>();
        
        // Adding elements to the collection
        c.add("Apple");
        c.add("Banana");
        c.add("Orange");
        
        System.out.println("Collection: " + c);
    }
}

Output
Collection: [Apple, Banana, Orange]

Collection Interface Declaration

public interface Collection<E> extends Iterable<E>

Here, E represents the type of elements stored in the collection.

Note: In the above syntax, we can replace any class with ArrayList if that class implements the Collection interface. 

Hierarchy of Collection Interface

The Collection interface is part of a hierarchy that extends Iterable, means collections can be traversed.

Collection Interface in Java-with-Examples

The hierarchy also includes several key sub-interfaces:

Sub-Interfaces of Collection Interface

The subInterfaces are sometimes called as Collection Types or SubTypes of Collection. These include the following:

1. List

The List interface represents an ordered collection that allows duplicates. It is implemented by classes like ArrayList, LinkedList, and Vector. Lists allow elements to be accessed by their index position.

public interface List<E> extends Collection<E>

2. Set

A set is an unordered collection of objects in which duplicate values cannot be stored. This set interface is implemented by various classes like HashSet, TreeSet, LinkedHashSet, etc.

public interface Set<E> extends Collection<E>

3. SortedSet

This interface is very similar to the set interface. The only difference is that this interface has extra methods that maintain the ordering of the elements. The sorted set interface extends the set interface and is used to handle the data which needs to be sorted. The class which implements this interface is TreeSet.

public interface SortedSet<E> extends Set<E>

4. Queue

The Queue interface represents a collection that follows FIFO (First-In-First-Out) order. It is implemented by classes like PriorityQueue, Deque, ArrayDeque, etc.

public interface Queue<E> extends Collection<E>

5. Deque

The Deque interface extends Queue and allows elements to be added or removed from both ends of the queue. It is implemented by ArrayDeque and LinkedList.

public interface Deque<E> extends Queue<E>

6. NavigableSet

The NavigableSet interface extends SortedSet and provides additional methods for navigation such as finding the closest element.

public interface NavigableSet<E> extends SortedSet<E>

Implementing Classes

Note: The Collection Interface is not limited to the above classes, there are many more classes.

Methods of Collection Interface

Method

Description

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

Method Declared in Iterable Interface:

Method

Description

forEach​(Consumer<? super T> action)Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

Java Collection Interface Examples

1. Adding Elements to a Collection 

The add(E e) and addAll(Collection c) methods provided by Collection can be used to add elements. 

// Adding elements to the Collection
import java.io.*;
import java.util.*;

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

        // create an empty ArrayList 
        // with an initial capacity
        Collection<Integer> l1 = new ArrayList<Integer>(5);

        // use add() method to 
        // add elements in the list
        l1.add(15);
        l1.add(20);
        l1.add(25);

        // prints all the elements available in list
        for (Integer n : l1) {
            System.out.println("Number = " + n);
        }

        // Creating another empty ArrayList
        Collection<Integer> l2 = new ArrayList<Integer>();

        // Appending the collection to the list
        l2.addAll(l1);

        // displaying the modified ArrayList
        System.out.println("The new ArrayList is: " + l2);
    }
}

Output
Number = 15
Number = 20
Number = 25
The new ArrayList is: [15, 20, 25]

2. Removing Elements from a Collections

The remove(E e) and removeAll(Collection c) methods can be used to remove a particular element or a Collection of elements from a collection. 

// Removing elements from a Collection
import java.util.*;

public class Geeks {
    public static void main(String[] argv) throws Exception {

        // Creating object of HashSet
        Collection<Integer> hs1 = new HashSet<Integer>();

        hs1.add(1);
        hs1.add(2);
        hs1.add(3);
        hs1.add(4);
        hs1.add(5);

        System.out.println("Initial set: " + hs1);
        
          // remove a particular element
          hs1.remove(4);
      
        System.out.println("Set after removing 4: " + hs1);
      
        // Creating another object of HashSet
        Collection<Integer> hs2 = new HashSet<Integer>();
        hs2.add(1);
        hs2.add(2);
        hs2.add(3);

        System.out.println("Collection Elements to be removed: " + hs2);

        // Removing elements from hs1
        // specified in hs2
        // using removeAll() method
        hs1.removeAll(hs2);

        System.out.println("Set 1 after removeAll() operation: " + hs1);
    }
}

Output
Initial set: [1, 2, 3, 4, 5]
Set after removing 4: [1, 2, 3, 5]
Collection Elements to be removed: [1, 2, 3]
Set 1 after removeAll() operation: [5]

3. Iterating over a Collection 

To iterate over the elements of Collection we can use iterator() method. 

// Iterating over a Collection
import java.util.*;

public class Geeks {

    public static void main(String[] args) {
      
        // Create and populate the list
        Collection<String> l = new LinkedList<>();

        l.add("Geeks");
        l.add("for");
        l.add("Geeks");

        // Displaying the list
        System.out.println("The list is:" + l);

        // Create an iterator for the list
        // using iterator() method
        Iterator<String> it = l.iterator();

        // Displaying the values after iterating
        // through the list
        System.out.println("\nThe iterator values" + " of list are: ");
        while (it.hasNext()) {
            System.out.print(it.next() + " ");
        }
    }
}

Output
The list is:[Geeks, for, Geeks]

The iterator values of list are: 
Geeks for Geeks 


Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg