Collection in Java

Deep dive into the Collection interface in Java: its contract, core methods, bulk operations, and how it underpins List, Set, and Queue.

Collection<E> is the root interface for almost every data structure in the Java Collections Framework. It sits one level above List, Set, and Queue, giving them a shared vocabulary of methods that all single-element containers must support. Writing code against Collection instead of a specific implementation makes your APIs flexible enough to accept any list, set, or queue without changes. Every developer working with Java needs a firm grasp of what Collection guarantees and what it deliberately leaves unspecified.

The Collection Contract

Collection<E> extends Iterable<E> and adds methods for querying and mutating a group of elements. The interface intentionally leaves certain behaviours (ordering, duplicates, null handling) unspecified so that List, Set, and Queue can each define their own rules.

Core Methods

Method Description
int size() Returns the number of elements.
boolean isEmpty() Returns true if the collection contains no elements.
boolean contains(Object o) Returns true if at least one element equals o.
boolean add(E e) Adds e; returns true if the collection changed.
boolean remove(Object o) Removes one occurrence of o; returns true if changed.
Iterator<E> iterator() Returns an iterator (inherited from Iterable).
void clear() Removes all elements.

Bulk Operations

Method Description
boolean containsAll(Collection<?> c) Returns true if this collection contains every element of c.
boolean addAll(Collection<? extends E> c) Adds all elements of c to this collection.
boolean removeAll(Collection<?> c) Removes all elements that are also in c.
boolean retainAll(Collection<?> c) Removes all elements not in c (set intersection).

Java 8+ Default Methods

Method Description
boolean removeIf(Predicate<? super E> filter) Removes all elements matching the predicate.
Stream<E> stream() Returns a sequential stream over the elements.
Stream<E> parallelStream() Returns a potentially parallel stream.
void forEach(Consumer<? super E> action) Inherited from Iterable; calls action for each element.

What Collection Does NOT Specify

  • Ordering: elements may or may not be in insertion order.
  • Duplicates: duplicates are permitted by List, forbidden by Set.
  • Null elements: some implementations allow nulls, others do not.
  • Thread safety: Collection itself is not thread-safe.

These are all defined by the sub-interfaces and their concrete implementations.

Example 1: Programming to Collection

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;

public class CollectionInterface {

    // Accepts any Collection — a List, a Set, or a Queue
    public static int countLongNames(Collection<String> names, int minLength) {
        int count = 0;
        for (String name : names) {
            if (name.length() >= minLength) count++;
        }
        return count;
    }

    public static void main(String[] args) {
        List<String> nameList = new ArrayList<>(List.of("Alice", "Bo", "Charlie", "Di"));
        Collection<String> nameSet = new HashSet<>(nameList);

        System.out.println(countLongNames(nameList, 4)); // 2 (Alice, Charlie)
        System.out.println(countLongNames(nameSet, 4));  // 2 (same count, any order)
    }
}

Example 2: Bulk Operations

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class BulkOps {
    public static void main(String[] args) {
        Collection<String> fruits = new ArrayList<>(List.of("apple", "banana", "cherry", "date"));
        Collection<String> toRemove = List.of("banana", "date");

        // removeAll: removes all elements present in toRemove
        fruits.removeAll(toRemove);
        System.out.println(fruits); // [apple, cherry]

        Collection<String> more = new ArrayList<>(List.of("apple", "elderberry", "fig"));

        // retainAll: keeps only elements present in both
        more.retainAll(fruits);
        System.out.println(more); // [apple]

        // removeIf (Java 8+): remove elements matching a predicate
        Collection<Integer> numbers = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6));
        numbers.removeIf(n -> n % 2 == 0);
        System.out.println(numbers); // [1, 3, 5]
    }
}

Common Mistakes

  • Removing from a collection during for-each iteration. Calling collection.remove(element) inside an enhanced for loop throws ConcurrentModificationException. Use iterator.remove() or collection.removeIf(predicate) instead.
  • Using Collection when a more specific interface is needed. If callers need index-based access, use List. If they need uniqueness guarantees, use Set. Using Collection is only appropriate when you genuinely accept any kind of collection.
  • Relying on add return value inconsistently. For a List, add(e) always returns true. For a Set, it returns false if the element already exists. Code that ignores this return value can miss duplicate-rejection silently.
  • Treating contains as O(1) for all implementations. ArrayList.contains is O(n). HashSet.contains is O(1) average. Choose your implementation based on how frequently you call contains.
  • Passing a raw Collection without a type parameter. Using the raw type Collection instead of Collection<String> disables generics checking and may cause ClassCastException at runtime.

Best Practices

  • Declare method parameters as Collection<E> (or a sub-interface) to be as permissive as possible without losing meaningful type information.
  • Use removeIf instead of an explicit iterator loop when removing elements based on a condition — it is cleaner and works correctly on all mutable collections.
  • When creating a defensive copy of an argument, pass it to new ArrayList<>(collection) to avoid holding a reference to a mutable object controlled by the caller.
  • Prefer isEmpty() over size() == 0; it is more readable and may be more efficient on some implementations.
  • Check contains performance before using it in a hot loop — if you need frequent membership tests, use a Set rather than a List.

Interview Questions

1. What is the Collection interface in Java?

Collection<E> is the root interface for groups of individual elements in the Java Collections Framework. It extends Iterable<E> and adds methods for adding, removing, querying, and bulk-operating on elements. It is the common supertype of List, Set, and Queue, but not Map.

2. What is the difference between Collection and Collections?

Collection is an interface; Collections is a utility class with only static methods. Collections.sort(), Collections.shuffle(), and Collections.unmodifiableList() are examples of utility methods that operate on collection objects but belong to the Collections class, not the Collection interface.

3. Why might add() return false?

The add(E e) method returns false when the collection did not change as a result of the call. This happens with Set implementations when you try to add an element that is already present. For a List, add always returns true because lists allow duplicates.

4. What does removeAll do, and what is its time complexity?

removeAll(Collection<?> c) removes every element in this that also appears in c. It iterates over this and calls c.contains(element) for each one, so the complexity is O(n * m) in the worst case if c is a List. Passing a HashSet as the argument reduces this to O(n) average because HashSet.contains is O(1).

5. When should you use retainAll versus removeAll?

Use retainAll(c) when you want the intersection — keeping only elements present in both collections. Use removeAll(c) when you want the difference — removing every element that appears in c. Both mutate the receiver collection in place and return true if the collection changed.

6. What is the difference between Collection.stream() and Collection.parallelStream()?

stream() returns a sequential stream that processes elements one at a time in the current thread. parallelStream() returns a stream that may split its work across multiple threads using the fork/join framework. Parallel streams improve throughput on large data with CPU-intensive operations but can cause race conditions if the stream operations have side effects on shared mutable state.

7. Can you add null to a Collection?

It depends on the implementation. ArrayList, LinkedList, and HashSet allow null elements. ArrayDeque, PriorityQueue, TreeSet, and most concurrent collections do not — they throw NullPointerException. The Collection interface itself does not mandate either behaviour.

Summary

  • Collection<E> extends Iterable<E> and is the common supertype of List, Set, and Queue.
  • It defines methods for size, membership, add, remove, and bulk operations.
  • Ordering, duplicates, and null handling are left to sub-interfaces and implementations.
  • Program to Collection in method signatures when you genuinely accept any single-element collection.
  • Java 8 added removeIf, stream, and parallelStream as default methods, making collection processing much more expressive.

Continue Learning

Previous: Iterable | Next: List

Was this guide helpful?

CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.