00:00

Collection Interface in Java – Methods with Examples

The Collection interface is the root interface of the Java Collections Framework for groups of single elements. List, Set and Queue all extend it, so every ArrayList, HashSet, ArrayDeque and similar class has the methods it defines.

Learning Collection well means you already know the basic operations of almost every collection class. This tutorial walks through its methods with runnable examples.

1. What Is the Collection Interface?

java.util.Collection describes the operations that make sense for any group of objects: add an element, remove it, check whether it is present, count the elements and loop over them. It says nothing about order, duplicates or indexes. Those rules are added by the sub-interfaces:

  • List adds order and indexes, and allows duplicates.
  • Set forbids duplicates.
  • Queue and Deque add head and tail operations for processing elements in order.

The JDK provides no class that implements Collection directly; every class implements one of its sub-interfaces.

2. Declaration and Hierarchy

java.util.Collection
public interface Collection<E> extends Iterable<E>

Collection extends Iterable, which is why every collection can be used in an enhanced for loop. E is the element type.

Hierarchy
Iterable
 └─ Collection
     ├─ SequencedCollection (Java 21)
     ├─ List   → ArrayList, LinkedList, Vector
     ├─ Set    → HashSet, LinkedHashSet, TreeSet
     └─ Queue  → PriorityQueue, ArrayDeque (through Deque)
Note: Map is not a Collection. It is a separate root interface for key–value pairs.

3. Adding Elements

add() returns a boolean that tells you whether the collection changed. A list always accepts the element and returns true. A set returns false for a duplicate, because nothing was added.

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

public class CollectionBasics {
    static void fill(Collection<String> c) {
        System.out.println("  add(Java):   " + c.add("Java"));
        System.out.println("  add(SQL):    " + c.add("SQL"));
        System.out.println("  add(Java):   " + c.add("Java"));   // duplicate
        System.out.println("  contents:    " + c + ", size=" + c.size());
    }

    public static void main(String[] args) {
        System.out.println("ArrayList (duplicates allowed):");
        fill(new ArrayList<>());
        System.out.println("HashSet (duplicates rejected):");
        fill(new HashSet<>());
    }
}
Output
ArrayList (duplicates allowed):
  add(Java):   true
  add(SQL):    true
  add(Java):   true
  contents:    [Java, SQL, Java], size=3
HashSet (duplicates rejected):
  add(Java):   true
  add(SQL):    true
  add(Java):   false
  contents:    [Java, SQL], size=2

Writing the method parameter as Collection<String> lets the same fill() method work with both a list and a set.

4. Checking and Removing Elements

contains() and containsAll() check membership, and remove() deletes one matching element. Like add(), remove() returns true only if something changed.

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

public class CollectionQueries {
    public static void main(String[] args) {
        Collection<String> cart = new ArrayList<>(List.of("pen", "book", "bag"));

        System.out.println("contains(book):         " + cart.contains("book"));
        System.out.println("containsAll([pen,bag]): " + cart.containsAll(List.of("pen", "bag")));
        System.out.println("containsAll([pen,cap]): " + cart.containsAll(List.of("pen", "cap")));
        System.out.println("isEmpty():              " + cart.isEmpty());

        System.out.println("remove(book):           " + cart.remove("book"));
        System.out.println("remove(cap):            " + cart.remove("cap"));
        System.out.println("now:                    " + cart);

        cart.clear();
        System.out.println("after clear():          " + cart + " isEmpty=" + cart.isEmpty());
    }
}
Output
contains(book):         true
containsAll([pen,bag]): true
containsAll([pen,cap]): false
isEmpty():              false
remove(book):           true
remove(cap):            false
now:                    [pen, bag]
after clear():          [] isEmpty=true

contains() and remove() use the elements' equals() method to find matches, so your own classes must override equals() (and hashCode()) for these methods to work as expected.

5. Bulk Operations: Union, Intersection and Difference

Bulk methods work with a whole collection at once. With a set, they behave like the set operations you learned in mathematics.

CollectionBulk.java
import java.util.Collection;
import java.util.List;
import java.util.TreeSet;

public class CollectionBulk {
    public static void main(String[] args) {
        Collection<Integer> a = new TreeSet<>(List.of(1, 2, 3, 4, 5, 6));
        Collection<Integer> b = List.of(4, 5, 6, 7, 8);

        Collection<Integer> union = new TreeSet<>(a);
        union.addAll(b);
        System.out.println("Union:        " + union);

        Collection<Integer> common = new TreeSet<>(a);
        common.retainAll(b);
        System.out.println("Intersection: " + common);

        Collection<Integer> diff = new TreeSet<>(a);
        diff.removeAll(b);
        System.out.println("Difference:   " + diff);

        Collection<Integer> odd = new TreeSet<>(union);
        boolean changed = odd.removeIf(n -> n % 2 == 0);
        System.out.println("Odd only:     " + odd + " (changed=" + changed + ")");
    }
}
Output
Union:        [1, 2, 3, 4, 5, 6, 7, 8]
Intersection: [4, 5, 6]
Difference:   [1, 2, 3]
Odd only:     [1, 3, 5, 7] (changed=true)
MethodResultSet operation
a.addAll(b)Elements in a or bUnion
a.retainAll(b)Elements in bothIntersection
a.removeAll(b)Elements in a but not in bDifference
a.removeIf(p)Elements of a that fail the testFilter

These methods change a itself, which is why the example copies the set first each time.

6. Iterating a Collection

Every collection can be looped over in four ways. Use the iterator's remove() (or removeIf()) when you need to delete elements during the loop.

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

public class CollectionIterate {
    public static void main(String[] args) {
        Collection<String> files = new ArrayList<>(List.of("a.txt", "b.log", "c.txt", "d.log"));

        // 1. for-each
        for (String f : files) System.out.print(f + " ");
        System.out.println();

        // 2. Iterator with safe removal
        Iterator<String> it = files.iterator();
        while (it.hasNext()) {
            if (it.next().endsWith(".log")) it.remove();
        }
        System.out.println("Without logs: " + files);

        // 3. forEach with a method reference
        files.forEach(System.out::println);

        // 4. Stream
        long count = files.stream().filter(f -> f.startsWith("c")).count();
        System.out.println("Files starting with c: " + count);
    }
}
Output
a.txt b.log c.txt d.log 
Without logs: [a.txt, c.txt]
a.txt
c.txt
Files starting with c: 1

7. Converting to an Array

toArray() copies the elements into a new array. The version without arguments always returns Object[]; pass an array or a constructor reference to get the right type.

CollectionToArray.java
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;

public class CollectionToArray {
    public static void main(String[] args) {
        Collection<String> tags = new LinkedHashSet<>(List.of("java", "spring", "sql"));

        Object[] objects = tags.toArray();                    // Object[]
        String[] typed = tags.toArray(new String[0]);         // String[]
        String[] typed11 = tags.toArray(String[]::new);       // Java 11+

        System.out.println(objects.getClass().getSimpleName() + " " + Arrays.toString(objects));
        System.out.println(typed.getClass().getSimpleName() + " " + Arrays.toString(typed));
        System.out.println(typed11.getClass().getSimpleName() + " " + Arrays.toString(typed11));
    }
}
Output
Object[] [java, spring, sql]
String[] [java, spring, sql]
String[] [java, spring, sql]

8. Writing Methods That Accept Any Collection

Using Collection as a parameter type makes a method reusable. Wildcards make it even more flexible:

  • Collection<?> accepts a collection of any element type (read-only use).
  • Collection<? extends Number> accepts collections of Integer, Double or any other Number.
WildcardMethods.java
import java.util.Collection;
import java.util.List;
import java.util.Set;

public class WildcardMethods {

    // Accepts a collection of anything
    static void printAll(Collection<?> items) {
        System.out.println(items.size() + " item(s): " + items);
    }

    // Accepts a collection of Integer, Double, Long ... (any Number)
    static double total(Collection<? extends Number> numbers) {
        double sum = 0;
        for (Number n : numbers) sum += n.doubleValue();
        return sum;
    }

    public static void main(String[] args) {
        printAll(List.of("a", "b"));
        printAll(Set.of(42));
        System.out.println("total(ints):    " + total(List.of(1, 2, 3)));
        System.out.println("total(doubles): " + total(List.of(1.5, 2.5)));
    }
}
Output
2 item(s): [a, b]
1 item(s): [42]
total(ints):    6.0
total(doubles): 4.0

9. All Collection Methods

MethodDescription
boolean add(E e)Adds an element; returns true if the collection changed.
boolean addAll(Collection<? extends E> c)Adds every element of another collection.
boolean remove(Object o)Removes one matching element.
boolean removeAll(Collection<?> c)Removes every element that is also in c.
boolean removeIf(Predicate<? super E> p)Removes every element that matches (Java 8).
boolean retainAll(Collection<?> c)Keeps only elements that are also in c.
void clear()Removes all elements.
boolean contains(Object o)Returns true if the element is present.
boolean containsAll(Collection<?> c)Returns true if every element of c is present.
int size()Number of elements.
boolean isEmpty()Returns true if there are no elements.
Iterator<E> iterator()Returns an iterator over the elements.
Object[] toArray()Copies the elements into an Object[].
<T> T[] toArray(T[] a)Copies the elements into a typed array.
<T> T[] toArray(IntFunction<T[]> g)Typed array from a generator such as String[]::new (Java 11).
Stream<E> stream(), parallelStream()Sequential or parallel stream (Java 8).
Spliterator<E> spliterator()Iterator that can split work for parallel processing.
void forEach(Consumer<? super T> action)Runs an action for each element (from Iterable).
boolean equals(Object o), int hashCode()Equality, defined more precisely by List and Set.

10. Optional Operations and UnsupportedOperationException

Methods that change a collection, such as add(), remove() and clear(), are called optional operations. A class may choose not to support them and throw UnsupportedOperationException instead. That is what happens with:

  • Immutable collections from List.of(), Set.of(), List.copyOf() and Set.copyOf().
  • Read-only views from Collections.unmodifiableCollection().
  • The fixed-size list from Arrays.asList() (for add() and remove()).
  • The keySet() and values() views of a Map (for add()).

11. Collection vs Collections

CollectionCollections
An interfaceA final utility class
Root of List, Set and QueueHas only static helper methods
Defines add(), remove(), size()…Provides sort(), max(), reverse(), unmodifiableList()…
You implement it (through a sub-interface)You call its methods: Collections.sort(list)

12. Best Practices

  • Use Collection<E> as a parameter type when your method only adds, removes, checks or loops, so callers can pass any list, set or queue.
  • Use the more specific List or Set type when your method relies on order, indexes or uniqueness.
  • Check the boolean results of add() and remove() when you need to know whether anything changed.
  • Prefer isEmpty() to size() == 0.
  • Prefer removeIf() to manual iterator loops for conditional removal.
  • Override equals() and hashCode() in classes stored in collections.

13. Summary

  • Collection is the root interface for lists, sets and queues, and extends Iterable.
  • It defines adding, removing, checking, counting, iterating, streaming and array conversion.
  • add() and remove() return whether the collection changed.
  • Bulk methods give union, intersection and difference.
  • Modifying methods are optional and may throw UnsupportedOperationException.
  • Map is not a Collection, and Collections is a separate utility class.

Related Tutorials

Reference: Java SE 21 API: java.util.Collection