• ↑↓ pour naviguer
  • pour ouvrir
  • pour sélectionner
  • ⌘ ⌥ ↵ pour ouvrir dans un panneau
  • ←→ pour naviguer
  • esc pour rejeter
⌘ '
raccourcis clavier

The Problem

Traditional iteration with loops is imperative and verbose — you tell the computer how to iterate (index variables, loop conditions) rather than what to compute. This leads to boilerplate code and makes parallel processing difficult. Collections needed a declarative, functional approach.

Core Idea

Lambda expressions provide concise syntax for anonymous functions: (parameters) -> expression. The Stream API processes collections in a functional pipeline: source → intermediate operations (filter, map, sorted) → terminal operation (collect, forEach, reduce). Method references (Class::method) provide even shorter syntax for simple lambdas.

How It Works

A stream represents a sequence of elements supporting sequential and parallel aggregate operations. Streams are lazy — intermediate operations are not executed until a terminal operation is invoked. The pipeline can be parallelized by calling .parallelStream() instead of .stream().

Visual Explanation

java_streams Source Collection [1, 2, 3, 4, 5, 6] Stream Stream Pipeline Source->Stream Filter filter(n → n % 2 == 0) [2, 4, 6] Stream->Filter intermediate Map map(n → n * n) [4, 16, 36] Filter->Map intermediate Collect collect(toList()) [4, 16, 36] Map->Collect terminal

Semantic Network

semantic_lambdas THIS Lambdas & Streams FI Functional Interfaces THIS--FI built from COLL Collections THIS--COLL built from THREAD Multithreading THIS--THREAD builds into PERF Performance THIS--PERF related

Key Properties

  • Declarative: Focus on what, not how — express intent directly
  • Lazy evaluation: Intermediate operations execute only when a terminal operation is invoked
  • Parallelism: parallelStream() splits work across multiple threads automatically
  • Immutability: Streams do not modify the source collection

Connections

Edge Cases & Gotchas

  • Stream reuse: A stream cannot be reused after a terminal operation — create a new one
  • Stateful lambdas: Avoid mutable state in lambda bodies (not thread-safe)
  • Performance: Streams have overhead vs loops for simple operations — use for complex pipelines
  • parallelStream() pitfalls: Shared mutable state in parallel streams causes data races