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
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.
Iterable
└─ Collection
├─ SequencedCollection (Java 21)
├─ List → ArrayList, LinkedList, Vector
├─ Set → HashSet, LinkedHashSet, TreeSet
└─ Queue → PriorityQueue, ArrayDeque (through Deque)
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.
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<>());
}
}
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.
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());
}
}
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.
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 + ")");
}
}
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)
| Method | Result | Set operation |
|---|---|---|
a.addAll(b) | Elements in a or b | Union |
a.retainAll(b) | Elements in both | Intersection |
a.removeAll(b) | Elements in a but not in b | Difference |
a.removeIf(p) | Elements of a that fail the test | Filter |
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.
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);
}
}
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.
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));
}
}
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 ofInteger,Doubleor any otherNumber.
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)));
}
}
2 item(s): [a, b] 1 item(s): [42] total(ints): 6.0 total(doubles): 4.0
9. All Collection Methods
| Method | Description |
|---|---|
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()andSet.copyOf(). - Read-only views from
Collections.unmodifiableCollection(). - The fixed-size list from
Arrays.asList()(foradd()andremove()). - The
keySet()andvalues()views of aMap(foradd()).
11. Collection vs Collections
| Collection | Collections |
|---|---|
| An interface | A final utility class |
| Root of List, Set and Queue | Has 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
ListorSettype when your method relies on order, indexes or uniqueness. - Check the
booleanresults ofadd()andremove()when you need to know whether anything changed. - Prefer
isEmpty()tosize() == 0. - Prefer
removeIf()to manual iterator loops for conditional removal. - Override
equals()andhashCode()in classes stored in collections.
13. Summary
Collectionis the root interface for lists, sets and queues, and extendsIterable.- It defines adding, removing, checking, counting, iterating, streaming and array conversion.
add()andremove()return whether the collection changed.- Bulk methods give union, intersection and difference.
- Modifying methods are optional and may throw
UnsupportedOperationException. Mapis not aCollection, andCollectionsis a separate utility class.
Related Tutorials
Reference: Java SE 21 API: java.util.Collection
Frequently Asked Questions (FAQ)
Q1. What is the Collection interface in Java?
It is the root interface of the Collections Framework for groups of single elements, in java.util. It defines common operations such as add(), remove(), contains(), size() and iterator(), and it is extended by List, Set and Queue.
Q2. Is Collection the root of the whole framework?
It is the root for element collections. Map is a separate root for key–value pairs. Above Collection sits Iterable, which only provides the ability to be looped over.
Q3. Why does Collection extend Iterable?
So that every collection can return an Iterator and be used in an enhanced for loop. Iterable also contributes the forEach() and spliterator() default methods.
Q4. Which class directly implements the Collection interface?
None in the JDK implements only Collection. Concrete classes implement a sub-interface such as List, Set or Queue. AbstractCollection is a skeleton class you can extend to write your own collection.
Q5. What does the boolean returned by add() mean?
true means the collection changed. Lists always return true. Sets return false when the element is already present. Bounded queues may throw an exception instead when they are full.
Q6. What is the difference between remove() and removeAll()?
remove(o) removes a single element that equals o. removeAll(c) removes every element that also appears in collection c, including all duplicates.
Q7. What is the difference between retainAll() and removeAll()?
They are opposites. retainAll(c) keeps only the elements that are in c (intersection). removeAll(c) deletes the elements that are in c (difference).
Q8. How does contains() decide if an element is present?
It uses equals(). Hash-based collections first use hashCode() to narrow the search, and sorted collections use compareTo() or a comparator. If your class does not override these methods correctly, contains() may return false for an equal object.
Q9. What is an optional operation?
A method that an implementation may decline to support by throwing UnsupportedOperationException. All methods that modify a collection are optional, which is how immutable and read-only collections work.
Q10. What is the difference between Collection and Collections?
Collection is an interface that collection classes implement. Collections is a utility class of static methods such as sort(), shuffle(), max() and synchronizedList().
Q11. How do I convert a Collection to an array?
String[] a = collection.toArray(new String[0]);
String[] b = collection.toArray(String[]::new); // Java 11+
The no-argument toArray() returns Object[], which cannot be cast to String[].
Q12. Why use Collection as a method parameter type?
It makes the method accept the widest range of inputs: lists, sets, queues and views such as map.values(). Use a narrower type like List only when the method needs list features such as indexes.
Q13. What does Collection<? extends Number> mean?
It is an upper-bounded wildcard: a collection whose elements are Number or any subclass, such as Integer or Double. You can read elements as Number, but you cannot add to it (except null), because the exact element type is unknown.
Q14. Does Collection have a get(index) method?
No. Indexes belong to List. A general collection, such as a HashSet, has no positions, so you read its elements with an iterator, a for-each loop or a stream.
Q15. What is the difference between stream() and parallelStream()?
stream() processes elements one after another on the current thread. parallelStream() may split the work across several threads of the common fork-join pool. Parallel streams help only for large, CPU-heavy workloads and must not change shared state.
Q16. Why does iterating and removing throw ConcurrentModificationException?
The iterator of most collections is fail-fast: it detects that the collection was changed by something other than itself and stops. Remove with iterator.remove() or removeIf() instead of calling collection.remove() inside the loop.
Q17. Are the collections returned by Map.keySet() and values() real Collections?
Yes. keySet() returns a Set and values() returns a Collection. They are views of the map: removing from them removes entries from the map, but add() is not supported.
Q18. How do I make a Collection read-only?
Wrap it with Collections.unmodifiableCollection(c), or use the specific versions for lists, sets and maps. For an independent immutable copy, use List.copyOf() or Set.copyOf().
Q19. When was the Collection interface introduced?
In JDK 1.2, together with the rest of the Collections Framework. Java 5 added generics, Java 8 added removeIf(), stream(), parallelStream() and spliterator(), and Java 11 added toArray(IntFunction).
Q20. How are two Collections compared with equals()?
The rules come from the sub-interfaces. Two lists are equal if they have the same elements in the same order. Two sets are equal if they have the same elements in any order. A list is never equal to a set, even with the same elements.