peek() — intermediate operation for debugging, returns same stream. forEach() — terminal operation for side-effects, consumes the stream. Think of peek() as a camera recording passersby without stopping them, while forEach() as a checkpoint that processes everyone who passes.
peek():
Stream — doesn't consume.1List<String> result = list.stream()2 .peek(s -> System.out.println("Processing: " + s))3 .filter(s -> s.length() > 3)4 .collect(Collectors.toList());
forEach():
void — consumes the stream.1list.stream()2 .filter(s -> s.length() > 3)3 .forEach(System.out::println);
Key difference: