Introduction to Java Stream Programming
What is a Stream? A Stream is a sequence of elements supporting sequential and parallel aggregate operations. It focuses on the “what” (declarative) rather than the “how” (imperative). Key Characteristics: No Storage: Streams don’t store data; they move it from a source (collection, array, I/O) through a pipeline. Functional: Operations don’t modify the source; they return new streams. Lazy Evaluation: Intermediate operations are only performed when a terminal operation is called. Possibly Infinite: Unlike collections, streams can be unbounded (e.g., a stream of random numbers). Stream Pipeline Stages Creation: list.stream(), Stream.of(a, b), IntStream.range(1, 10). Intermediate Operations: (Lazy) filter, map, sorted, distinct. Terminal Operations: (Triggers execution) collect, forEach, reduce, count, anyMatch. Common Operations Creation Stream.generate(Math::random).limit(10) Stream.iterate(0, n -> n + 2).limit(5) (Generates 0, 2, 4, 6, 8) Intermediate filter(Predicate): Selects elements. map(Function): Transforms elements. flatMap(Function): Flattens a stream of streams into a single stream. peek(Consumer): Performs an action for each element (mainly for debugging). Terminal collect(Collectors.toList()): Accumulates elements into a collection. reduce(BinaryOperator): Combines elements into a single result (e.g., sum). allMatch/anyMatch/noneMatch: Returns a boolean based on a condition. The Optional Class Many terminal operations return an Optional<T> to avoid NullPointerException if the stream is empty. ...