Senior
Tell me about Stream API: types of operations, the difference between map and flatMap
sobes.tech AI
Answer from AI
Stream API in Java is a powerful tool for working with collections and data sequences, allowing you to write declarative code for data processing.
Types of operations:
- Intermediate — return a new Stream, enabling chaining of operations, for example:
filter(),map(),flatMap(),sorted(),distinct(). - Terminal — conclude the chain and return a result or side effect, for example:
collect(),forEach(),reduce(),count().
Difference between map and flatMap:
maptransforms each element of the stream into one other element, for example, from a string to its length.flatMaptransforms each element into a stream of elements, then "flattens" these streams into a single stream.
Example:
List<String> words = Arrays.asList("hello", "world");
// map: transform each word into an array of characters
Stream<char[]> mapped = words.stream().map(word -> word.toCharArray());
// flatMap: transform each word into a Stream<Character> and merge
Stream<Character> flatMapped = words.stream()
.flatMap(word -> word.chars().mapToObj(c -> (char)c));
// flatMap makes working with nested structures more convenient
Thus, flatMap is useful when you need to obtain multiple elements from a single element for further processing.