Java 8 – Stream mapToLong() method

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

1. Stream mapToLong() method :

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



2. Stream mapToLong() method examples :

2.1 Convert String to long :

  • A list contains String elements
  • We are going to convert these String elements present in List to primitive long-valued sequence using Stream’s mapToLong() method which returns LongStream using 3 different approaches
  • 1st approach – using lambda expression i.e.; mapToLong(str -> Long.parseLong(str))
  • 2nd approach – using Method reference i.e.; mapToLong(Long::parseLong)
  • 3rd approach – implementing Anonymous Function for ToLongFunction<String>
  • Finally, we can use Stream’s forEach() method to iterate/print primitive long values to the console

ConvertStringToLong.java

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

import java.util.Arrays;
import java.util.List;
import java.util.function.ToLongFunction;
import java.util.stream.LongStream;

public class ConvertStringToLong {

	public static void main(String[] args) {

		// list of Strings
		List<String> numbers = Arrays.asList(
				"12345678", 
				"87654321", 
				"24680246",
				"13579735",
				"10203040"
				);

		// 1.1 string to long using mapToLong() - lambda expression
		LongStream longStreamLEx = numbers
				.stream()	
				.mapToLong(str -> Long.parseLong(str)); // mapToLong()

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


		// 2.1 string to long using mapToLong() - method reference
		LongStream longStreamMRef = numbers
				.stream()
				.mapToLong(Long::parseLong); // mapToLong()

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


		// 3.1 string to long using mapToLong() - Anonymous Function
		LongStream longStreamAnonymousFn = numbers
				.stream()
				.mapToLong(new ToLongFunction<String>() {

					@Override
					public long applyAsLong(String str) {
						return Long.parseLong(str);
					}
				});

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

Output:

1. String to long using mapToLong() - Lambda Expression :- 

12345678
87654321
24680246
13579735
10203040

2. String to long using mapToLong() - Method Reference :- 

12345678
87654321
24680246
13579735
10203040

3. String to long using mapToLong() - Anonymous Function :- 

12345678
87654321
24680246
13579735
10203040

2.2 Convert String to long and Square them :

  • A list contains numbers in String format
  • We are converting these String elements present in the list to long numbers and Squaring them using Stream’s mapToLong() method which returns LongStream
  • Finally, we can use Stream’s forEach() method to iterate/print squared long values to the console

GetSquaresForLongNumbers.java

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

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

public class GetSquaresForLongNumbers {

	public static void main(String[] args) {

		// list of Strings
		List<String> numbers = Arrays.asList(
				"12345678", 
				"87654321", 
				"24680246",
				"13579735",
				"10203040"
				);

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


		// 1.1 string to long using mapToLong() - lambda expression
		LongStream longStreamLEx = numbers
				.stream()	
				.mapToLong(
						str -> Long.parseLong(str) * Long.parseLong(str)
						); // mapToLong()

		// 1.2 print to console
		System.out.println("\nSquares of long numbers using mapToLong() -"
				+ " Lambda Expression :- \n");
		longStreamLEx.forEach(num -> System.out.println(num));
	}
}

Output:

Original numbers in String format :- 

12345678
87654321
24680246
13579735
10203040

Squares of long numbers using mapToLong() - Lambda Expression :- 

152415765279684
7683279989971041
609114542620516
184409202670225
104102025241600

2.3 Get long numbers divisible by 10 :

  • A list contains numbers in String format
  • We are converting these String elements present in the list to long numbers using Stream’s mapToLong() method which returns LongStream and then filtering those values which are divisible by 10
  • Mapping :- using mapToLong() method i.e.; mapToLong(str -> Long.parseLong(str))
  • Filtering :- using filter() method i.e.; filter(num -> num % 10 == 0)
  • Finally, we can use Stream’s forEach() method to iterate/print converted/filtered long values to the console

GetLongNumbersDivisibleBy10.java

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

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

public class GetLongNumbersDivisibleBy10 {

	public static void main(String[] args) {

		// 1. list of Strings
		List<String> numbers = Arrays.asList(
				"123456780", 
				"876543211", 
				"246802460",
				"135797350",
				"102030401"
				);

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


		// 2. string to long using mapToLong() and filter()
		LongStream longStreamLEx = numbers
				.stream() // get Sequential stream
				.mapToLong(str -> Long.parseLong(str)) // mapToLong()
				.filter(num -> num % 10 == 0); // filter()

		// 2.1 print to console
		System.out.println("\nMapped/filtered long numbers divisible by 10 :- \n");
		longStreamLEx.forEach(num -> System.out.println(num));
	}
}

Output:

Original numbers in String format :- 

123456780
876543211
246802460
135797350
102030401

Mapped/filtered long numbers divisible by 10 :- 

123456780
246802460
135797350

2.4 Get Ids from list of Products- :

  • A list contains Product information with attributes like id, name and its price
  • We are intended to extract only Id which is of long-type from Product list
  • We are going to use Method reference i.e.; mapToLong(Product::getId) to get all Product Ids
  • Finally, we can use Stream’s forEach() method to iterate/print Product Id 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()
}

GetAllProductId.java

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

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

public class GetAllProductId {

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

		return Arrays.asList(
				new Product(100000001L, "Wheat", 36.89),
				new Product(100000002L, "Rice", 58.19),
				new Product(100000003L, "Lentils", 102.45),
				new Product(100000004L, "Oil",  164.75),
				new Product(100000005L, "Vegetables", 45.50)
				);
	}

	// 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 all Product Id
		LongStream productIds = products
				.stream() // get Sequential stream
				.mapToLong(Product::getId); // mapToLong()

		// 2.1 print to console all Product Id
		System.out.println("\nProduct Ids :- \n");
		productIds.forEach(System.out::println);
	}
}

Output:

All Products :- 

Product [id=100000001, name=Wheat, price=36.89]
Product [id=100000002, name=Rice, price=58.19]
Product [id=100000003, name=Lentils, price=102.45]
Product [id=100000004, name=Oil, price=164.75]
Product [id=100000005, name=Vegetables, price=45.5]

Product Ids :- 

100000001
100000002
100000003
100000004
100000005

2.5 Get summary statistics of long numbers :

  • A list contains numbers in String format
  • First, we are going to convert these String elements present in the list to long numbers using Stream’s mapToLong() 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 LongSummaryStatistics 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

StatisticsForLongNumbers.java

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

import java.util.Arrays;
import java.util.List;
import java.util.LongSummaryStatistics;

public class StatisticsForLongNumbers {

	public static void main(String[] args) {

		// 1. list of Strings
		List<String> numbers = Arrays.asList(
				"12345678", 
				"87654321", 
				"24680246",
				"13579735",
				"10203040"
				);

		// 1.1 get statistics
		LongSummaryStatistics longSummaryStatistics = numbers
				.stream() // get sequential stream
				.mapToLong(Long::parseLong) // mapToLong()
				.summaryStatistics(); // summaryStatistics()

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


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

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

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

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

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

Output:

LongSummaryStatistics{count=5, sum=148463020, min=10203040, 
average=29692604.000000, max=87654321}

Sum = 148463020

Count = 5

Average = 2.9692604E7

Max value = 87654321

Min value = 10203040

Related Articles :

References :

Happy Coding !!
Happy Learning !!

Java 8 - Stream mapToDouble() method
Java 8 - Stream mapToInt() method