Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Collection — size, emptiness, and streams

java.util.Collection<E> describes a group of elements. Learn how to check size and emptiness and distinguish sequential from possibly parallel streams in Java SE 21.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

Collection<E>
int size()
boolean isEmpty()
default Stream<E> stream()
default Stream<E> parallelStream()

java.util.Collection<E> is the root interface of the collection hierarchy, extending Iterable<E>. Ordering, duplicate allowance, and support for null depend on the particular collection. Some modifying operations are optional and may throw UnsupportedOperationException.

Collection.size() returns the element count as an int, capped at Integer.MAX_VALUE. Collection.isEmpty() returns true when the collection contains no elements; use it when asking whether the collection is empty.

Collection.stream() creates a sequential stream. Collection.parallelStream() returns a possibly parallel stream: the default implementation creates a parallel one, but the contract permits a sequential one. A stream does not store elements; a terminal operation such as sum() triggers pipeline computation. Create a new stream for another traversal.

Do not modify the source while a pipeline executes unless the source supports concurrent modification. Avoid shared mutable state in lambdas. In the example, both pipelines calculate the same sum without side effects; printing happens only after each computation finishes.

Examples

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

public class Main {
    public static void main(String[] args) {
        Collection<Integer> numbers = List.of(2, 4, 6);
        System.out.println(numbers.size());
        System.out.println(numbers.isEmpty());
        System.out.println(numbers.stream().mapToInt(Integer::intValue).sum());
        System.out.println(numbers.parallelStream().mapToInt(Integer::intValue).sum());
    }
}

Result

3
false
12
12

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources