In this article, we will discuss Stream’s flatMapToInt() method in detail with examples and explanation
1. Stream flatMapToInt() method :
- This Stream method is an intermediate operation which returns an
IntStream
consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element - Each mapped stream is
closed
after its contents have been placed into this stream - If a mapped stream is
null
an empty stream is used, instead - Stream’s flatMapToInt() method is stateless which means it is non-interfering with other elements in the stream
- Method signature :- IntStream flatMapToInt(Function<? super T, ? extends IntStream> mapper)
- Where IntStream is a sequence of primitive int-valued elements and T is the type of Stream elements
2. Stream flatMapToInt() method examples :
2.1 Flatten List<List<Integer>> to IntStream
- A outer main list contains 3 sub-lists and in each sub-list there are 3 or 4 integer elements
- We are converting outer main list into IntStream using flatMapToInt() method which returns flattened integer numbers
- Finally, we are finding summary statistics of these integer numbers using IntStream‘s summaryStatistics() method while peeking into each elements using Stream’s peek() method
package net.bench.resources.stream.flatmaptoint.example;
import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.stream.IntStream;
public class StreamFlatMapToIntForList {
public static void main(String[] args) {
// 3 lists defined
List<Integer> childList1 = Arrays.asList(1, 2, 3);
List<Integer> childList2 = Arrays.asList(4, 5, 6);
List<Integer> childList3 = Arrays.asList(7, 8, 9, 10);
// Outer main-list contains 3 child sub-list
List<List<Integer>> mainList = Arrays.asList(
childList1,
childList2,
childList3
);
// flatMapToInt()
IntStream intStream = mainList
.stream()
.flatMapToInt(list -> list.stream()
.mapToInt(num -> num));
// iterate/print to console
System.out.println("Flattened list using flatMapToInt() method :- \n");
// IntSummaryStatistics
IntSummaryStatistics intSummaryStatistics = intStream
.peek(System.out::println) // print to console
.summaryStatistics(); // get summary statistics
// summary statistics for flattened list
System.out.println("\nSummary statistics for flattened list :- \n\n"
+ intSummaryStatistics);
}
}
Output:
Flattened list using flatMapToInt() method :-
1
2
3
4
5
6
7
8
9
10
Summary statistics for flattened list :-
IntSummaryStatistics{count=10, sum=55, min=1, average=5.500000, max=10}
2.2 Flatten 2-D String[][] array to IntStream
- A 2-d String[][] array defined where in each array there are integer numbers defined in String format
- We are converting 2-d String[][] array into IntStream using flatMapToInt() method which returns flattened integer numbers
- Finally, we are finding summary statistics of these integer numbers using IntStream‘s summaryStatistics() method while peeking into each elements using Stream’s peek() method
package net.bench.resources.stream.flatmaptoint.example;
import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.stream.IntStream;
public class StreamFlatMapToIntForArrays {
public static void main(String[] args) {
// 2d String[][] array
String[][] stringArray2D = {
{"1", "2", "3"},
{"4", "5", "6"},
{"7", "8", "9", "10"}
};
// flatMapToInt()
IntStream intStream = Arrays.stream(stringArray2D)
.flatMapToInt(array -> Arrays.stream(array)
.mapToInt(Integer::new));
// iterate/print to console
System.out.println("Flattened 2-d Array using flatMapToInt() method :- \n");
// IntSummaryStatistics
IntSummaryStatistics intSummaryStatistics = intStream
.peek(System.out::println) // print to console
.summaryStatistics(); // get summary statistics
// summary statistics for flattened 2-d Array
System.out.println("\nSummary statistics for flattened 2-d Array :- \n\n"
+ intSummaryStatistics);
}
}
Output:
Flattened 2-d Array using flatMapToInt() method :-
1
2
3
4
5
6
7
8
9
10
Summary statistics for flattened 2-d Array :-
IntSummaryStatistics{count=10, sum=55, min=1, average=5.500000, max=10}
2.3 Flatten 2-D String[][] array and get String length
- A 2-d String[][] array defined where in each array there are 3 or 4 Strings
- We are converting 2-d String[][] array into IntStream of String length using flatMapToInt() method which returns flattened integer number of each String length
package net.bench.resources.stream.flatmaptoint.example;
import java.util.Arrays;
import java.util.stream.IntStream;
public class StreamFlatMapToIntForStringLength {
public static void main(String[] args) {
// 2d String[][] array
String[][] stringArray2D = {
{"Suresh", "Naresh", "Rajesh"},
{"Abdul", "Santosh", "Anbu"},
{"Krish", "Viraj", "Rishi", "Aditya"}
};
// flatMapToInt()
IntStream intStream = Arrays.stream(stringArray2D)
.flatMapToInt(array -> Arrays.stream(array)
.mapToInt(String::length));
// flattened Array using flatMapToInt()
System.out.println("Length of Flattened 2-d String[][] Array "
+ "using flatMapToInt() method :- \n");
// iterate/print to console
intStream.forEach(System.out::println);
}
}
Output:
Length of Flattened 2-d String[][] Array using flatMapToInt() method :-
6
6
6
5
7
4
5
5
5
6
2.4 Flatten List<Student[]> to IntStream
- There are 3 Student[] array defined
- In each Student[] array, there are 2 Students defined with their attributes such as rollNo, name and their age
- And all these 3 Student[] array are added to a List
- We are converting List of Student[] array extracting age information into IntStream using flatMapToInt() method which returns flattened integer number
- Also, we are finding summary statistics of Student Age using IntStream‘s summaryStatistics() method while peeking into each elements using Stream’s peek() method
Student.java
package net.bench.resources.stream.flatmaptoint.example;
public class Student {
// member variables
private int rollNumber;
private String name;
private int age;
// constructors
// getters & setters
// toString()
}
StreamFlatMapToIntForStudentAge.java
package net.bench.resources.stream.flatmaptoint.example;
import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.stream.IntStream;
public class StreamFlatMapToIntForStudentAge {
public static void main(String[] args) {
// class 1 - Student array
Student[] studentArray1 = new Student[] {
new Student(101, "Pravin", 20),
new Student(102, "Sachin", 21)
};
// class 2 - Student array
Student[] studentArray2 = new Student[] {
new Student(201, "Harshata", 19),
new Student(202, "Siddhesh", 23)
};
// class 3 - Student array
Student[] studentArray3 = new Student[] {
new Student(301, "Shweta", 18),
new Student(302, "Nikita", 17)
};
// list of Student[] array
List<Student[]> studentList = Arrays.asList(
studentArray1,
studentArray2,
studentArray3
);
// flatMapToInt()
IntStream intStream = studentList
.stream()
.flatMapToInt(studentArray -> Arrays.stream(studentArray)
.mapToInt(student -> student.getAge()));
// extract Student age in all classes and statistics
System.out.println("Student Age in all classes "
+ "using flatMapToInt() method :- \n");
// IntSummaryStatistics
IntSummaryStatistics intSummaryStatistics = intStream
.peek(System.out::println) // print to console
.summaryStatistics(); // get summary statistics
// summary statistics for flattened list
System.out.println("\nSummary statistics for Student age :- \n\n"
+ intSummaryStatistics);
}
}
Output:
Student Age in all classes using flatMapToInt() method :-
20
21
19
23
18
17
Summary statistics for Student age :-
IntSummaryStatistics{count=6, sum=118, min=17, average=19.666667, max=23}
References:
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html
- https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html
Happy Coding !!
Happy Learning !!