map() — an intermediate operation that transforms each element. collect() — a terminal operation that accumulates elements into a result container. They work together: map() transforms the data, collect() gathers the results.
map():
Stream<R> — another stream.1Stream<Integer> lengths = words.stream()2 .map(String::length); // Stream<Integer> — lazy, not yet processed3// Nothing happens until a terminal operation is called
collect():
1List<Integer> lengths = words.stream()2 .map(String::length)3 .collect(Collectors.toList()); // triggers processing, returns List
How they work together:
1// Complete pipeline: filter → map → collect2List<String> result = orders.stream()3 .filter(o -> o.getTotal() > 100) // intermediate: filter4 .map(Order::getCustomerName) // intermediate: transform5 .distinct() // intermediate: deduplicate6 .collect(Collectors.toList()); // terminal: collect
Key difference: