🔹 flatMap()
and its variants
✅ flatMap(Function<T, Stream<R>> mapper)
Used to:
- Transform each element in the stream into a stream of values
- Flatten those inner streams into one continuous stream
Example:
List<String> words = List.of("hello", "world");
List<String> letters = words.stream()
.flatMap(word -> Arrays.stream(word.split("")))
.collect(Collectors.toList());
System.out.println(letters); // [h, e, l, l, o, w, o, r, l, d]
Here:
"hello"
→["h", "e", "l", "l", "o"]
"world"
→["w", "o", "r", "l", "d"]
- Then
flatMap
merges all letters into a single stream
✅ flatMapToInt(Function<T, IntStream> mapper)
Used when the result is primitive int
values.
Example:
List<String> numbers = List.of("1,2", "3,4");
IntStream intStream = numbers.stream()
.flatMapToInt(s -> Arrays.stream(s.split(",")).mapToInt(Integer::parseInt));
intStream.forEach(System.out::print); // 1234
✅ flatMapToDouble(Function<T, DoubleStream> mapper)
Same as above, but for double
:
List<String> doubles = List.of("1.5,2.5", "3.0");
DoubleStream doubleStream = doubles.stream()
.flatMapToDouble(s -> Arrays.stream(s.split(",")).mapToDouble(Double::parseDouble));
doubleStream.forEach(System.out::println);
✅ flatMapToLong(Function<T, LongStream> mapper)
Same, for long
values:
List<String> longs = List.of("100,200", "300");
LongStream longStream = longs.stream()
.flatMapToLong(s -> Arrays.stream(s.split(",")).mapToLong(Long::parseLong));
longStream.forEach(System.out::println);
🔸 When to Use flatMap
vs map
Use map() when… | Use flatMap() when… |
---|---|
You return one value per element | You return a stream or collection per element |
No need to flatten anything | You need to flatten nested structures |