In this article, we will discuss Stream’s flatMapToLong() method in detail with examples and explanation
1. Stream flatMapToLong() method :
- This Stream method is an intermediate operation which returns an
LongStream
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 flatMapToLong() method is stateless which means it is non-interfering with other elements in the stream
- Method signature :- LongStream flatMapToLong(Function<? super T, ? extends LongStream> mapper)
- Where LongStream is a sequence of primitive long-valued elements and T is the type of Stream elements
2. Stream flatMapToLong() method examples :
2.1 Flatten List<List<Long>> to LongStream
- A outer main list contains 3 sub-lists and in each sub-list there are 3 or 4 long numbers
- We are converting outer main list into LongStream using flatMapToLong() method which returns flattened long numbers
- Finally, we are finding summary statistics of these long numbers using LongStream‘s summaryStatistics() method while peeking into each elements using Stream’s peek() method
package net.bench.resources.stream.flatmaptolong.example;
import java.util.Arrays;
import java.util.List;
import java.util.LongSummaryStatistics;
import java.util.stream.LongStream;
public class StreamFlatMapToLongForList {
public static void main(String[] args) {
// 3 lists defined
List<Long> childList1 = Arrays.asList(1997L, 1998L, 1999L);
List<Long> childList2 = Arrays.asList(2004L, 2005L, 2006L);
List<Long> childList3 = Arrays.asList(2011L, 2017L, 2019L, 2021L);
// Outer main-list contains 3 child sub-list
List<List<Long>> mainList = Arrays.asList(
childList1,
childList2,
childList3
);
// flatMapToLong()
LongStream longStream = mainList
.stream()
.flatMapToLong(list -> list.stream()
.mapToLong(num -> num));
// iterate/print to console
System.out.println("Flattened list using flatMapToLong() method :- \n");
// LongSummaryStatistics
LongSummaryStatistics longSummaryStatistics = longStream
.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"
+ longSummaryStatistics);
}
}
Output:
Flattened list using flatMapToLong() method :-
1997
1998
1999
2004
2005
2006
2011
2017
2019
2021
Summary statistics for flattened list :-
LongSummaryStatistics{count=10, sum=20077, min=1997, average=2007.700000, max=2021}
2.2 Flatten 2-D String[][] array to LongStream
- A 2-d String[][] array defined where in each array there are long numbers in String format
- We are converting 2-d String[][] array into LongStream using flatMapToLong() method which returns flattened long numbers
- Finally, we are finding summary statistics of these long numbers using LongStream‘s summaryStatistics() method while peeking into each elements using Stream’s peek() method
package net.bench.resources.stream.flatmaptolong.example;
import java.util.Arrays;
import java.util.LongSummaryStatistics;
import java.util.stream.LongStream;
public class StreamFlatMapToLongForArrays {
public static void main(String[] args) {
// 2d String[][] array
String[][] stringArray2D = {
{"1991", "1992", "1993"},
{"2007", "2008", "2009"},
{"2011", "2017", "2019", "2022"}
};
// flatMapToLong()
LongStream longStream = Arrays.stream(stringArray2D)
.flatMapToLong(array -> Arrays.stream(array)
.mapToLong(Long::new));
// iterate/print to console
System.out.println("Flattened 2-d Array using flatMapToLong() method :- \n");
// LongSummaryStatistics
LongSummaryStatistics longSummaryStatistics = longStream
.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"
+ longSummaryStatistics);
}
}
Output:
Flattened 2-d Array using flatMapToLong() method :-
1991
1992
1993
2007
2008
2009
2011
2017
2019
2022
Summary statistics for flattened 2-d Array :-
LongSummaryStatistics{count=10, sum=20069, min=1991, average=2006.900000, max=2022}
2.3 Flatten List<Product[]> to LongStream
- There are 3 Product[] array defined
- In each Product[] array, there are 2 Products defined with their attributes such as id, name, quantity and their price
- And all these 3 Product[] array are added to a List
- We are converting List of Product[] array extracting quantity information (which is of type long) into LongStream using flatMapToLong() method which returns flattened long number
- Also, we are finding summary statistics of Product quantity using LongStream‘s summaryStatistics() method while peeking into each elements using Stream’s peek() method
Product.java
package net.bench.resources.stream.flatmaptolong.example;
public class Product {
// member variables
private int id;
private String name;
private long quantity;
private double price;
// 4-arg parameterized constructor
// getters and setters
// toString() method
}
StreamFlatMapToLongForProductQuantity.java
package net.bench.resources.stream.flatmaptolong.example;
import java.util.Arrays;
import java.util.List;
import java.util.LongSummaryStatistics;
import java.util.stream.LongStream;
public class StreamFlatMapToLongForProductQuantity {
public static void main(String[] args) {
// Category 1 - Product array
Product[] productArray1 = new Product[] {
new Product(101, "Wheat", 1089L, 36.89),
new Product(102, "Rice", 502L, 58.19)
};
// Category 2 - Product array
Product[] productArray2 = new Product[] {
new Product(103, "Lentils", 803L, 102.45),
new Product(104, "Oil", 208L, 164.75)
};
// Category 3 - Product array
Product[] productArray3 = new Product[] {
new Product(105, "Vegetables", 303L, 45.50),
new Product(106, "Meat", 404L, 731.56)
};
// list of Product[] array
List<Product[]> productList = Arrays.asList(
productArray1,
productArray2,
productArray3
);
// flatMapToLong()
LongStream longStream = productList
.stream()
.flatMapToLong(productArray -> Arrays.stream(productArray)
.mapToLong(product -> product.getQuantity()));
// extract Product Quantity from all categories
System.out.println("Product Quantity from all categories "
+ "using flatMapToLong() method :- \n");
// LongSummaryStatistics
LongSummaryStatistics longSummaryStatistics = longStream
.peek(System.out::println) // print to console
.summaryStatistics(); // get summary statistics
// summary statistics for flattened list
System.out.println("\nSummary statistics for Product Quantity :- \n\n"
+ longSummaryStatistics);
}
}
Output:
Product Quantity from all categories using flatMapToLong() method :-
1089
502
803
208
303
404
Summary statistics for Product Quantity :-
LongSummaryStatistics{count=6, sum=3309, min=208, average=551.500000, max=1089}
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 !!