Stream API

Site Admin · 11 Sep 2026 · 9 views

Declarative Data Processing

Streams let you process collections with a pipeline of operations - filter, map, sort, collect - instead of writing loops with temporary variables.

Loop vs Stream

List<Integer> scores = List.of(61, 88, 45, 92, 70);

// Old style
int total = 0;
for (int s : scores) {
    if (s > 60) total += s;
}
System.out.println(total);

// Stream style
int sum = scores.stream()
    .filter(s -> s > 60)                // keep passing scores
    .mapToInt(Integer::intValue)
    .sum();
System.out.println(sum);

Common Operations

import java.util.*;
import java.util.stream.*;

List<String> names = List.of("Anjali", "Ravi", "Anil", "Bala", "Amar");

// filter + sorted + collect
List<String> aNames = names.stream()
    .filter(n -> n.startsWith("A"))
    .sorted()
    .collect(Collectors.toList());
System.out.println(aNames);

// map transforms each element
List<Integer> lengths = names.stream()
    .map(String::length)
    .collect(Collectors.toList());
System.out.println(lengths);

// count and anyMatch
long longCount = names.stream().filter(n -> n.length() > 4).count();
boolean hasRavi = names.stream().anyMatch(n -> n.equals("Ravi"));

Grouping

List<String> words = List.of("cat", "dog", "cat", "bird");
Map<String, Long> counts =
    words.stream().collect(Collectors.groupingBy(w -> w, Collectors.counting()));
System.out.println(counts); // {cat=2, bird=1, dog=1}

Streams are Lazy

Intermediate operations (filter, map) do not run until a terminal operation (collect, count, forEach) is called. The pipeline is computed in one pass.

names.stream()
    .filter(n -> n.length() > 3)   // intermediate - lazy
    .forEach(System.out::println); // terminal - triggers work

Key Points

  • Streams chain lazy operations; a terminal call triggers execution.
  • filter drops, map transforms, collect gathers the results.
  • groupingBy builds maps grouped by a classifier.
Share this post:

Comments (0)

Please login or register to comment.