Collection Interface in Java

Naveen AnamaneniUpdated · 4 min read
easyJava 25javacollections

The Collection interface in Java is the root interface of the collection hierarchy. It is used to represent a group of objects, and it declares the methods that every list, set and queue supports, such as add, remove, contains and size. In this lesson, you will learn its declaration, its most important methods, and how to use them.

Declaration

Declaration
public interface Collection<E> extends Iterable<E>

Here, E is the type of the elements. Collection extends Iterable, so every collection can be used in a for-each loop. The interfaces List, Set and Queue extend Collection.

Methods of the Collection Interface

MethodDescription
boolean add(E e)It is used to add an element to the collection.
boolean addAll(Collection<? extends E> c)It is used to add all elements of another collection.
boolean remove(Object o)It is used to remove one occurrence of the given element.
boolean removeAll(Collection<?> c)It is used to remove all elements that are also in another collection.
boolean removeIf(Predicate<? super E> filter)It is used to remove every element that matches a condition.
boolean retainAll(Collection<?> c)It is used to keep only the elements that are also in another collection.
boolean contains(Object o)It is used to check whether an element is present.
int size()It returns the number of elements.
boolean isEmpty()It checks whether the collection has no elements.
void clear()It removes all elements.
Object[] toArray()It returns the elements in an array.
Iterator<E> iterator()It returns an iterator over the elements.
Stream<E> stream()It returns a stream of the elements.

Example: Common Collection Methods

Let's see an example of these methods on a list of student names.

CollectionMethods.java▶ Try it
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
 
public class CollectionMethods {
    public static void main(String[] args) {
        Collection<String> c = new ArrayList<>(
            List.of("Navika", "Srihitha", "Advitha"));
        System.out.println(c.size() + " " + c.contains("Advitha")
            + " " + c.isEmpty());
 
        c.remove("Srihitha");
        c.add("Anamaneni");
        System.out.println(c);
 
        c.removeIf(name -> name.startsWith("A"));
        System.out.println(c);
    }
}
Output
3 true false
[Navika, Advitha, Anamaneni]
[Navika]

Explanation: The collection starts with three names. size() returns 3, contains("Advitha") returns true, and isEmpty() returns false. Then "Srihitha" is removed and "Anamaneni" is added. Finally, removeIf removes every name that starts with "A", leaving only "Navika". The expression name -> name.startsWith("A") is a lambda, a short way to pass a condition; lambdas are explained later in the course.

Bulk Operations

The ...All methods work with a whole collection at once:

Bulk.java▶ Try it
import java.util.ArrayList;
import java.util.List;
 
public class Bulk {
    public static void main(String[] args) {
        List<String> classA = new ArrayList<>(List.of("Navika", "Srihitha"));
        List<String> classB = List.of("Srihitha", "Advitha");
 
        List<String> all = new ArrayList<>(classA);
        all.addAll(classB);
        System.out.println("addAll: " + all);
 
        List<String> common = new ArrayList<>(classA);
        common.retainAll(classB);
        System.out.println("retainAll: " + common);
 
        List<String> onlyA = new ArrayList<>(classA);
        onlyA.removeAll(classB);
        System.out.println("removeAll: " + onlyA);
    }
}
Output
addAll: [Navika, Srihitha, Srihitha, Advitha]
retainAll: [Srihitha]
removeAll: [Navika]

Explanation: addAll joins the two lists. retainAll keeps only the names present in both, like an intersection. removeAll removes the names that are in class B, leaving the names only in class A.

Common Mistakes

Calling add on a list made with List.of. It throws UnsupportedOperationException; copy it into an ArrayList first.

Expecting remove(element) to remove every copy. It removes only the first occurrence; use removeIf or removeAll.

Confusing retainAll and removeAll. retainAll keeps the common elements; removeAll deletes them.

Practice

  1. Easy: Create a collection of five numbers, remove all even numbers with removeIf, and print the size.
  2. Harder: Given two lists of subjects for Navika and Advitha, print the subjects they share and the subjects only Navika has.

Quick check: Collection interface

4 questions
1What does Collection extend?
2Which method keeps only the common elements?
3What does remove("Navika") remove from a list with two "Navika" entries?
4Which method removes elements matching a condition?

Key Takeaways

Was this tutorial helpful?

Lesson 253 of 482