1. Introduction
In this quick tutorial, we will learn how to use the flatMapToInt() method of the Java Stream API. flatMapToInt() is used to convert elements of a stream that are collections or arrays of integers (or objects that can be mapped to integers) into an IntStream. This is particularly useful for processing nested structures or combining multiple arrays or collections into a single stream of integers.
Key Points
1. flatMapToInt() maps elements of a stream to IntStream objects and flattens the result into a single IntStream.
2. It is ideal for scenarios where you need to transform nested collections or arrays of integers into a single stream.
3. This method facilitates operations on flattened integer data, such as summing or finding averages.
2. Program Steps
1. Create a Stream containing collections or arrays of integers.
2. Apply flatMapToInt() to transform these into a single IntStream.
3. Perform operations such as sum, average, or other reductions on the IntStream.
3. Code Program
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class StreamFlatMapToIntExample {
public static void main(String[] args) {
// Creating a stream of integer arrays
Stream<int[]> arraysStream = Stream.of(new int[]{1, 2}, new int[]{3, 4}, new int[]{5, 6});
// Using flatMapToInt to convert and flatten the stream into an IntStream
IntStream intStream = arraysStream.flatMapToInt(IntStream::of);
// Calculating the sum of all integers in the stream
int sum = intStream.sum();
System.out.println("Sum of all integers: " + sum);
}
}
Output:
Sum of all integers: 21
Explanation:
1. Stream.of(new int[]{1, 2}, new int[]{3, 4}, new int[]{5, 6}) creates a stream of arrays, each containing a pair of integers.
2. arraysStream.flatMapToInt(IntStream::of) applies the flatMapToInt method, which maps each array into an IntStream of its elements and then flattens these streams into a single IntStream.
3. intStream.sum() computes the sum of all elements in the flattened IntStream, yielding the total sum of all integers in the initial arrays.
Comments
Post a Comment
Leave Comment