Java 8 – Stream flatMapToDouble() method

In this article, we will discuss Stream’s flatMapToDouble() method in detail with examples and explanation

1. Stream flatMapToDouble() method :

  • This Stream method is an intermediate operation which returns an DoubleStream 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 flatMapToDouble() method is stateless which means it is non-interfering with other elements in the stream
  • Method signature :- DoubleStream flatMapToDouble(Function<? super T, ? extends DoubleStream> mapper)
  • Where DoubleStream is a sequence of primitive double-valued elements and T is the type of Stream elements



2. Stream flatMapToDouble() method examples :

2.1 Flatten List<List<Double>> to DoubleStream

  • A outer main list contains 3 sub-lists and in each sub-list there are 3 or 4 double values
  • We are converting outer main list into DoubleStream using flatMapToDouble() method which returns flattened double values
  • Finally, we are finding summary statistics of these double values using DoubleStream‘s summaryStatistics() method while peeking into each elements using Stream’s peek() method
package net.bench.resources.stream.flatmaptodouble.example;

import java.util.Arrays;
import java.util.DoubleSummaryStatistics;
import java.util.List;
import java.util.stream.DoubleStream;

public class StreamFlatMapToDoubleForList {

	public static void main(String[] args) {

		// 3 lists defined
		List<Double> childList1 = Arrays.asList(19.97, 66.67, 65.34);
		List<Double> childList2 = Arrays.asList(79.43, 93.54, 98.76);
		List<Double> childList3 = Arrays.asList(43.93, 54.32, 90.12, 86.57);


		// Outer main-list contains 3 child sub-list
		List<List<Double>> mainList = Arrays.asList(
				childList1, 
				childList2, 
				childList3
				);


		// flatMapToDouble()
		DoubleStream doubleStream = mainList
				.stream()
				.flatMapToDouble(list -> list.stream()
						.mapToDouble(num -> num));


		// iterate/print to console
		System.out.println("Flattened list using flatMapToDouble() method :- \n");


		// DoubleSummaryStatistics
		DoubleSummaryStatistics doubleSummaryStatistics = doubleStream
				.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" 
				+ doubleSummaryStatistics);
	}
}

Output:

Flattened list using flatMapToDouble() method :- 

19.97
66.67
65.34
79.43
93.54
98.76
43.93
54.32
90.12
86.57

Summary statistics for flattened list :- 

DoubleSummaryStatistics{count=10, sum=698.650000, min=19.970000, 
average=69.865000, max=98.760000}

2.2 Flatten 2-D String[][] array to DoubleStream

  • A 2-d String[][] array defined where in each array there are double values defined in String format
  • We are converting 2-d String[][] array into DoubleStream using flatMapToDouble() method which returns flattened double values
  • Finally, we are finding summary statistics of these double values using DoubleStream‘s summaryStatistics() method while peeking into each elements using Stream’s peek() method
package net.bench.resources.stream.flatmaptodouble.example;

import java.util.Arrays;
import java.util.DoubleSummaryStatistics;
import java.util.stream.DoubleStream;

public class StreamFlatMapToDoubleForArrays {

	public static void main(String[] args) {

		// 2d String[][] array
		String[][] stringArray2D = {
				{"97.19", "76.53", "80.65"}, 
				{"53.79", "83.45", "89.67"}, 
				{"96.43", "65.43", "91.23", "57.86"}
		};


		// flatMapToDouble()
		DoubleStream doubleStream = Arrays.stream(stringArray2D)
				.flatMapToDouble(array -> Arrays.stream(array)
						.mapToDouble(Double::new));


		// iterate/print to console
		System.out.println("Flattened 2-d Array using flatMapToDouble() method :- \n");


		// DoubleSummaryStatistics
		DoubleSummaryStatistics doubleSummaryStatistics = doubleStream
				.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" 
				+ doubleSummaryStatistics);
	}
}

Output:

Flattened 2-d Array using flatMapToDouble() method :- 

97.19
76.53
80.65
53.79
83.45
89.67
96.43
65.43
91.23
57.86

Summary statistics for flattened 2-d Array :- 

DoubleSummaryStatistics{count=10, sum=792.230000, min=53.790000, 
average=79.223000, max=97.190000}

2.3 Flatten List<Product[]> to DoubleStream

  • 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 price information (which is of type double) into DoubleStream using flatMapToDouble() method which returns flattened double values
  • Also, we are finding summary statistics of Product price using DoubleStream‘s summaryStatistics() method while peeking into each elements using Stream’s peek() method

Product.java

package net.bench.resources.stream.flatmaptodouble.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
}

StreamFlatMapToDoubleForProductPrice.java

package net.bench.resources.stream.flatmaptodouble.example;

import java.util.Arrays;
import java.util.DoubleSummaryStatistics;
import java.util.List;
import java.util.stream.DoubleStream;

public class StreamFlatMapToDoubleForProductPrice {

	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
				);


		// flatMapToDouble()
		DoubleStream doubleStream = productList
				.stream()
				.flatMapToDouble(productArray -> Arrays.stream(productArray)
						.mapToDouble(product -> product.getPrice()));


		// extract Product Price from all categories
		System.out.println("Product Price from all categories "
				+ "using flatMapToDouble() method :- \n");


		// DoubleSummaryStatistics
		DoubleSummaryStatistics doubleSummaryStatistics = doubleStream
				.peek(System.out::println) // print to console
				.summaryStatistics(); // get summary statistics


		// summary statistics for flattened list
		System.out.println("\nSummary statistics for Product Price :- \n\n" 
				+ doubleSummaryStatistics);
	}
}

Output:

Product Price from all categories using flatMapToDouble() method :- 

36.89
58.19
102.45
164.75
45.5
731.56

Summary statistics for Product Price :- 

DoubleSummaryStatistics{count=6, sum=1139.340000, min=36.890000, 
average=189.890000, max=731.560000}

References:

Happy Coding !!
Happy Learning !!

Java 8 - How to remove duplicates from LinkedList ?
Java 8 - Stream flatMapToLong() method