What is the difference between `forEach()` and `map()` in Streams?
Both forEach()
and map()
are methods in Java Streams, but they serve different purposes and have distinct behaviors.
forEach()
- Purpose: The
forEach()
method is used to perform an action on each element of the stream. - Side Effects: It is a terminal operation, meaning it triggers the processing of the stream and can have side effects (e.g., printing, modifying external state).
- Usage: It does not transform the stream but allows you to apply an action on each element, such as printing or logging.
- Return Type: It does not return a new stream; instead, it returns
void
.
List<String> words = Arrays.asList("Java", "Python", "C++");
words.stream().forEach(System.out::println); // Prints each word
map()
- Purpose: The
map()
method is used to transform each element of the stream into another form (typically of a different type). - No Side Effects: It is a non-terminal operation that returns a new stream with transformed elements. It does not modify the original stream.
- Usage: It is used for applying a function to each element, such as converting, extracting values, or changing the type.
- Return Type: It returns a new stream of transformed elements.
List<String> words = Arrays.asList("Java", "Python", "C++");
List<Integer> lengths = words.stream()
.map(String::length) // Maps each word to its length
.collect(Collectors.toList());
Key Differences
forEach()
is used for performing actions on elements (e.g., printing or updating a state) and is a terminal operation, whereasmap()
is used for transforming elements and returns a new stream for further operations.- Side Effects:
forEach()
often has side effects (e.g., modifying variables or printing), whilemap()
is meant for pure transformations without side effects.
In summary, forEach()
is used to apply an action to each element, while map()
is used to transform each element into a new form and return a new stream.