forEach() — executes an action on each element (side-effect). collect() — accumulates elements into a result container. Think of forEach() as a security guard checking each person as they pass, while collect() as a bouncer gathering people into a room.
forEach():
Consumer on each element.void.1list.stream()2 .filter(x -> x > 10)3 .forEach(System.out::println);
collect():
1List<Integer> result = list.stream()2 .filter(x -> x > 10)3 .collect(Collectors.toList());
Performance considerations:
When to use:
1// forEach: side-effects2orders.stream()3 .filter(o -> o.isOverdue())4 .forEach(notificationService::sendReminder);56// collect: build result7List<Order> overdueOrders = orders.stream()8 .filter(Order::isOverdue)9 .collect(Collectors.toList());
Common mistake:
1// WRONG: using forEach to build a list2List<String> result = new ArrayList<>();3list.stream().filter(s -> s.length() > 3).forEach(result::add);4// This works but is not idiomatic and may have issues in parallel streams56// CORRECT: use collect7List<String> result = list.stream()8 .filter(s -> s.length() > 3)9 .collect(Collectors.toList());