Sobes.tech
Middle

What are the methods flatMap(), flatMapToInt(), flatMapToDouble(), and flatMapToLong() used for in the Stream API?

sobes.tech AI

Answer from AI

The methods flatMap(), flatMapToInt(), flatMapToDouble(), and flatMapToLong() in the Stream API are used for flattening streams. They transform each element of the input stream into zero or more elements of another stream, and then merge these resulting streams into a single flat stream.

Main differences:

  • flatMap(): Takes a function that returns Stream<R>, and merges these streams into one Stream<R>.
  • flatMapToInt(): Takes a function that returns IntStream, and merges these streams into one IntStream.
  • flatMapToDouble(): Takes a function that returns DoubleStream, and merges these streams into one DoubleStream.
  • flatMapToLong(): Takes a function that returns LongStream, and merges these streams into one LongStream.

Example of using flatMap():

// Original list of lists of strings
List<List<String>> nestedList = Arrays.asList(
    Arrays.asList("one", "two"),
    Arrays.asList("three", "four"),
    Arrays.asList("five")
);

// Using flatMap to flatten into a single stream of strings
List<String> flatList = nestedList.stream()
    .flatMap(Collection::stream) // Each inner list is converted into a stream, then all are merged
    .collect(Collectors.toList());

// The result flatList will be ["one", "two", "three", "four", "five"]

Example of using flatMapToInt():

// Original list of lists of integers
List<List<Integer>> nestedInts = Arrays.asList(
    Arrays.asList(1, 2),
    Arrays.asList(3),
    Arrays.asList(4, 5, 6)
);

// Using flatMapToInt to flatten into a single IntStream
int sumOfAll = nestedInts.stream()
    .flatMapToInt(list -> list.stream().mapToInt(Integer::intValue)) // Convert List<Integer> to IntStream
    .sum(); // Sum all elements in the IntStream

// The result sumOfAll will be 21

Comparison table:

Method Input function returns Resulting stream
flatMap() Stream<R> Stream<R>
flatMapToInt() IntStream IntStream
flatMapToDouble() DoubleStream DoubleStream
flatMapToLong() LongStream LongStream

The main purpose of these methods is to transform each element of the stream into zero or more elements of another stream and then merge these streams into one. This is often used for working with nested data structures or when a single input element can produce multiple output elements.