Java 8 – Stream mapToInt() method

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

1. Stream mapToInt() method :

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



2. Stream mapToInt() method examples :

2.1 Get String length

  • A list contains String elements
  • We are going to find length of each String present in the list using Stream’s mapToInt() method which returns IntStream using 3 different approaches
  • 1st approach – using lambda expression i.e.; mapToInt(str -> str.length())
  • 2nd approach – using Method reference i.e.; mapToInt(String::length)
  • 3rd approach – implementing Anonymous Function for ToIntFunction<String>
  • Finally, we can use Stream’s forEach() method to iterate/print length of each String to the console
package net.bench.resources.stream.maptoint.example;

import java.util.Arrays;
import java.util.List;
import java.util.function.ToIntFunction;
import java.util.stream.IntStream;

public class GetStringLength {

	public static void main(String[] args) {

		// list of Strings
		List<String> techStack = Arrays.asList(
				"java", 
				"spring", 
				"hibernate",
				"webservices",
				"databases"
				);

		// 1.1 get string length using mapToInt - lambda expression
		IntStream intStreamLEx = techStack
				.stream()
				.mapToInt(str -> str.length()); // mapToInt

		// 1.2 print to console
		System.out.println("1. String length using mapToInt() -"
				+ " Lambda Expression :- \n");
		intStreamLEx.forEach(System.out::println);


		// 2.1 get string length using mapToInt - method reference
		IntStream intStreamMRef = techStack
				.stream()
				.mapToInt(String::length); // mapToInt

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


		// 3.1 get string length using mapToInt - Anonymous Function
		IntStream intStreamAnonymousFn = techStack
				.stream()
				.mapToInt(new ToIntFunction<String>() { // mapToInt

					@Override
					public int applyAsInt(String str) {
						return str.length();
					}
				});

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

Output:

1. String length using mapToInt() - Lambda Expression :- 

4
6
9
11
9

2. String length using mapToInt() - Method Reference :- 

4
6
9
11
9

3. String length using mapToInt() - Anonymous Function :- 

4
6
9
11
9

2.2 Convert String to int

  • A list contains numbers in String format
  • We are converting these String elements present in the list to int numbers using Stream’s mapToInt() method which returns IntStream
  • 1st approach – using lambda expression i.e.; mapToInt(str -> Integer.parseInt(str))
  • 2nd approach – using Method reference i.e.; mapToInt(Integer::parseInt)
  • Finally, we can use Stream’s forEach() method to iterate/print converted primitive int values to the console
package net.bench.resources.stream.maptoint.example;

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

public class ConvertStringToInt {

	public static void main(String[] args) {

		// list of Strings
		List<String> numbers = Arrays.asList(
				"19", 
				"63", 
				"97",
				"93",
				"86"
				);

		// 1.1 string to int using mapToInt - lambda expression
		IntStream intStreamLEx = numbers
				.stream()	
				.mapToInt(str -> Integer.parseInt(str)); // mapToInt

		// 1.2 print to console
		System.out.println("1. String to int using mapToInt() -"
				+ " Lambda Expression :- \n");
		intStreamLEx.forEach(System.out::println);


		// 2.1 string to int using mapToInt - method reference
		IntStream intStreamMRef = numbers
				.stream()
				.mapToInt(Integer::parseInt); // mapToInt

		// 2.2 print to console
		System.out.println("\n2. String to int using mapToInt() -"
				+ " Method Reference :- \n");
		intStreamMRef.forEach(System.out::println);
	}
}

Output:

1. String to int using mapToInt() - Lambda Expression :- 

19
63
97
93
86

2. String to int using mapToInt() - Method Reference :- 

19
63
97
93
86

2.3 Convert String to int and Square them

  • A list contains numbers in String format
  • We are converting these String elements present in the list to int numbers and Squaring them using Stream’s mapToInt() method which returns IntStream
  • Finally, we can use Stream’s forEach() method to iterate/print squared int values to the console
package net.bench.resources.stream.maptoint.example;

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

public class GetSquaresForIntegerNumbers {

	public static void main(String[] args) {

		// list of Strings
		List<String> numbers = Arrays.asList(
				"7", 
				"19",
				"63",
				"86", 
				"97"
				);

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


		// 1.1 string to int using mapToInt() - lambda expression
		IntStream intStreamLEx = numbers
				.stream()	
				.mapToInt(
						str -> Integer.parseInt(str) * Integer.parseInt(str)
						); // mapToInt()

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

Output:

Original numbers in String format :- 

7
19
63
86
97

Squares of int numbers using mapToInt() - Lambda Expression :- 

49
361
3969
7396
9409

2.4 Get Age Info from list of Students

  • A list contains Student information with attributes like rollNo, name and their age
  • We are intended to extract only Age information from Student list
  • 1st approach – using lambda expression i.e.; mapToInt(student -> student.getAge())
  • 2nd approach – using Method reference i.e.; mapToInt(Student::getAge)
  • Finally, we can use Stream’s forEach() method to iterate/print Student Age information to the console

Student.java

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

public class Student {

	// member variables
	private int rollNumber;
	private String name;
	private int age;

	// 3-arg parameterized constructor

	// getters & setters

	// toString()
}

GetStudentAgeInfo.java

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

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

public class GetStudentAgeInfo {

	public static void main(String[] args) {

		// list of students
		List<Student> students = Arrays.asList(
				new Student(1, "Viraj", 17),
				new Student(2, "Krish", 18),
				new Student(3, "Rishi", 16),
				new Student(4, "Suresh", 23),
				new Student(5, "Aditya", 21)
				);

		// print original Student list
		System.out.println("Student list :- \n");
		students.stream().forEach(System.out::println);


		// 1.1 get Student age using mapToInt - Lambda Expression
		IntStream ageStreamLEx = students
				.stream()
				.mapToInt(student -> student.getAge());

		// 1.2 print to console
		System.out.println("\n1. Student Age using mapToInt() -"
				+ " Lambda Expression :- \n");
		ageStreamLEx.forEach(System.out::println);


		// 1.2 get Student age using mapToInt - Method Reference
		IntStream ageStreamMRef = students
				.stream()
				.mapToInt(Student::getAge);

		// 1.2 print to console
		System.out.println("\n2. Student Age using mapToInt() -"
				+ " Method Reference :- \n");
		ageStreamMRef.forEach(System.out::println);
	}
}

Output:

Student list :- 

Student [rollNumber=1, name=Viraj, age=17]
Student [rollNumber=2, name=Krish, age=18]
Student [rollNumber=3, name=Rishi, age=16]
Student [rollNumber=4, name=Suresh, age=23]
Student [rollNumber=5, name=Aditya, age=21]

1. Student Age using mapToInt() - Lambda Expression :- 

17
18
16
23
21

2. Student Age using mapToInt() - Method Reference :- 

17
18
16
23
21

2.5 Get summary statistics of numbers

  • A list contains numbers in String format
  • First, we are going to convert these String elements present in the list to int numbers using Stream’s mapToInt() 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 IntSummaryStatistics 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.maptoint.example;

import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;

public class StreamStatisticsForListOfNumbers {

	public static void main(String[] args) {

		// list of Strings
		List<String> numbers = Arrays.asList(
				"19", 
				"63", 
				"97",
				"93",
				"86"
				);

		// get statistics
		IntSummaryStatistics intSummaryStatistics = numbers
				.stream()
				.mapToInt(str -> Integer.parseInt(str))
				.summaryStatistics(); // summaryStatistics

		// Summary statistics
		System.out.println(intSummaryStatistics);

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

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

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

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

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

Output:

IntSummaryStatistics{count=5, sum=358, min=19, average=71.600000, max=97}

Sum = 358

Count = 5

Average = 71.6

Max value = 97

Min value = 19

References:

Happy Coding !!
Happy Learning !!

Java 8 - Stream mapToLong() method
Java 8 - Stream reduce() method with examples