Java 8 – Stream mapToDouble() method

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

1. Stream mapToDouble() method :

  • This Stream method is an intermediate operation which returns a DoubleStream consisting of the results of applying the given function to the elements of this stream
  • Stream’s mapToDouble() method is stateless which means it is non-interfering with other elements in the stream
  • Method signature :- DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper)
  • Where DoubleStream is a sequence of primitive double-valued elements and T is the type of Stream elements



2. Stream mapToDouble() method examples :

2.1 Convert String to double values

  • A list contains String elements
  • We are going to convert these String elements present in List to primitive double-valued sequence using Stream’s mapToDouble() method which returns DoubleStream using 3 different approaches
  • 1st approach – using lambda expression i.e.; mapToDouble(str -> Double.parseDouble(str))
  • 2nd approach – using Method reference i.e.; mapToDouble(Double::parseDouble)
  • 3rd approach – implementing Anonymous Function for ToDoubleFunction<String>
  • Finally, we can use Stream’s forEach() method to iterate/print primitive double values to the console
package net.bench.resources.stream.maptodouble.example;

import java.util.Arrays;
import java.util.List;
import java.util.function.ToDoubleFunction;
import java.util.stream.DoubleStream;

public class ConvertStringToDouble {

	public static void main(String[] args) {

		// list of Strings
		List<String> numbers = Arrays.asList(
				"1.34", 
				"19.32",
				"0.97",
				"10.87", 
				"5.67"
				);

		// 1.1 string to double using mapToDouble() - lambda expression
		DoubleStream doubleStreamLEx = numbers
				.stream()	
				.mapToDouble(str -> Double.parseDouble(str)); // mapToDouble()

		// 1.2 print to console
		System.out.println("1. String to double using mapToDouble() -"
				+ " Lambda Expression :- \n");
		doubleStreamLEx.forEach(num -> System.out.println(num));


		// 2.1 string to double using mapToDouble() - method reference
		DoubleStream doubleStreamMRef = numbers
				.stream()
				.mapToDouble(Double::parseDouble); // mapToDouble()

		// 2.2 print to console
		System.out.println("\n2. String to double using mapToDouble() -"
				+ " Method Reference :- \n");
		doubleStreamMRef.forEach(System.out::println);


		// 3.1 string to long using mapToDouble() - Anonymous Function
		DoubleStream dblStreamAnonymousFn = numbers
				.stream()
				.mapToDouble(new ToDoubleFunction<String>() {

					@Override
					public double applyAsDouble(String str) {
						return Double.parseDouble(str);
					}
				});

		// 3.2 print to console
		System.out.println("\n3. String to double using mapToDouble() -"
				+ " Anonymous Function :- \n");
		dblStreamAnonymousFn.forEach(System.out::println);
	}
}

Output:

1. String to double using mapToDouble() - Lambda Expression :- 

1.34
19.32
0.97
10.87
5.67

2. String to double using mapToDouble() - Method Reference :- 

1.34
19.32
0.97
10.87
5.67

3. String to double using mapToDouble() - Anonymous Function :- 

1.34
19.32
0.97
10.87
5.67

2.2 Get double numbers divisible by 1.5

  • A list contains numbers in String format
  • We are converting these String elements present in the List to double numbers using Stream’s mapToDouble() method which returns DoubleStream and then filtering those values which are divisible by 1.5
  • Mapping :- using mapToDouble() method i.e.; mapToDouble(str -> Double.parseDouble(str))
  • Filtering :- using filter() method i.e.; filter(num -> num % 1.5 == 0)
  • Finally, we can use Stream’s forEach() method to iterate/print converted/filtered double values to the console
package net.bench.resources.stream.maptodouble.example;

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

public class GetDoubleNumbersDivisibleBy1Point5 {

	public static void main(String[] args) {

		// list of Strings
		List<String> numbers = Arrays.asList(
				"1.50", 
				"19.50",
				"0.90",
				"10.50", 
				"5.67"
				);

		// 1.1 print original numbers
		System.out.println("Original numbers in String format :- \n");
		numbers.forEach(System.out::println);


		// 2. string to double using mapToDouble() and filter()
		DoubleStream doubleStreamLEx = numbers
				.stream() // get Sequential stream
				.mapToDouble(str -> Double.parseDouble(str)) // mapToDouble()
				.filter(num -> num % 1.5 == 0); // filter()

		// 2.1 print to console
		System.out.println("\nMapped double numbers divisible by 1.5 :- \n");
		doubleStreamLEx.forEach(num -> System.out.println(num));
	}
}

Output:

Original numbers in String format :- 

1.50
19.50
0.90
10.50
5.67

Mapped double numbers divisible by 1.5 :- 

1.5
19.5
10.5

2.3 Get Square of double numbers

  • A list contains numbers in String format
  • We are converting these String elements present in the List to double numbers and squaring them using Stream’s mapToDouble() method which returns DoubleStream
  • Finally, we can use Stream’s forEach() method to iterate/print converted/squared double values to the console
package net.bench.resources.stream.maptodouble.example;

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

public class GetSquaresForDoubleNumbers {

	public static void main(String[] args) {

		// list of Strings
		List<String> numbers = Arrays.asList(
				"1.34", 
				"19.32",
				"0.97",
				"10.87", 
				"5.67"
				);

		System.out.println("1. Original numbers in String format :- \n");
		numbers.forEach(System.out::println);


		// 1.1 string to double using mapToDouble() - lambda expression
		DoubleStream doubleStreamLEx = numbers
				.stream()	
				.mapToDouble(
						str -> Double.parseDouble(str) * Double.parseDouble(str)
						); // mapToDouble()

		// 1.2 print to console
		System.out.println("\n2. Squares of double numbers using mapToDouble() -"
				+ " Lambda Expression :- \n");
		doubleStreamLEx.forEach(num -> System.out.println(num));
	}
}

Output:

1. Original numbers in String format :- 

1.34
19.32
0.97
10.87
5.67

2. Squares of double numbers using mapToDouble() - Lambda Expression :- 

1.7956000000000003
373.2624
0.9409
118.15689999999998
32.1489

2.4 Get price of all Products from List

  • A list contains Product information with attributes like id, name and its price
  • We are intended to extract only price which is of type double from Product list
  • We are going to use Method reference i.e.; mapToDouble(Product::getPrice) to get price of all Products
  • Finally, we can use Stream’s forEach() method to iterate/print Product price information to the console

Product.java

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

public class Product {

	// member variables
	private long id;
	private String name;
	private double price;

	// 3-arg parameterized constructor

	// getters and setters

	// toString()
}

GetPriceOfAllProducts.java

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

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

public class GetPriceOfAllProducts {

	// List of Products
	private static List<Product> getProductList() {

		return Arrays.asList(
				new Product(100000111L, "Rice", 58.19),
				new Product(100000222L, "Wheat", 36.89),
				new Product(100000333L, "Lentils", 102.45),
				new Product(100000444L, "Oil",  164.75),
				new Product(100000555L, "Vegetables", 45.56)
				);
	}

	// main() method
	public static void main(String[] args) {

		// 1. List of Products
		List<Product> products = getProductList();

		// 1.1 print to console all Product information
		System.out.println("All Products :- \n");
		products.forEach(System.out::println);


		// 2. get price of all Products
		DoubleStream productIds = products
				.stream() // get Sequential stream
				.mapToDouble(Product::getPrice); // mapToDouble()

		// 2.1 print to console all Product Id
		System.out.println("\nPrice of All Products :- \n");
		productIds.forEach(System.out::println);


		// 3.1 product price in increasing order
		System.out.println("\nProduct Price in Ascending order :- \n");
		products
		.stream()
		.mapToDouble(Product::getPrice)
		.sorted()
		.forEach(System.out::println);
	}
}

Output:

All Products :- 

Product [id=100000111, name=Rice, price=58.19]
Product [id=100000222, name=Wheat, price=36.89]
Product [id=100000333, name=Lentils, price=102.45]
Product [id=100000444, name=Oil, price=164.75]
Product [id=100000555, name=Vegetables, price=45.56]

Price of All Products :- 

58.19
36.89
102.45
164.75
45.56

Product Price in Ascending order :- 

36.89
45.56
58.19
102.45
164.75

2.5 Get summary statistics of Double numbers

  • A list contains numbers in String format
  • First, we are going to convert these String elements present in the List to double numbers using Stream’s mapToDouble() method
  • Then invoking summaryStatistics() method on the result to get various information like count, sum, min, average and max
  • We can also get these information individually/separately using different methods provided in the DoubleSummaryStatistics class like,
    1. getSum() method to find sum of elements
    2. getCount() method to find number of elements
    3. getAverage() method to find average
    4. getMax() method to find max element
    5. getMin() method to find min element
package net.bench.resources.stream.maptodouble.example;

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

public class StatisticsForDoubleNumbers {

	public static void main(String[] args) {

		// list of Strings
		List<String> numbers = Arrays.asList(
				"1.34", 
				"19.32",
				"0.97",
				"10.87", 
				"5.67"
				);

		// 1.1 get statistics
		DoubleSummaryStatistics dblSummaryStatistics = numbers
				.stream() // get sequential stream
				.mapToDouble(Double::parseDouble) // mapToDouble()
				.summaryStatistics(); // summaryStatistics()

		// 1.2 Summary statistics
		System.out.println(dblSummaryStatistics);


		// 2.1 print Sum individually
		System.out.println("\nSum = " 
				+ dblSummaryStatistics.getSum());

		// 2.2 print Count individually
		System.out.println("\nCount = " 
				+ dblSummaryStatistics.getCount());

		// 2.3 print Average individually
		System.out.println("\nAverage = " 
				+ dblSummaryStatistics.getAverage());

		// 2.4 print Max value individually
		System.out.println("\nMax value = " 
				+ dblSummaryStatistics.getMax());

		// 2.5 print Min value individually
		System.out.println("\nMin value = " 
				+ dblSummaryStatistics.getMin());
	}
}

Output:

DoubleSummaryStatistics{count=5, sum=38.170000, min=0.970000, 
average=7.634000, max=19.320000}

Sum = 38.17

Count = 5

Average = 7.634

Max value = 19.32

Min value = 0.97

References:

Happy Coding !!
Happy Learning !!

Java 8 - Stream flatMapToInt() method
Java 8 - Stream mapToLong() method