Java 8 – Stream map() method with examples

In this article, we will discuss Stream map() method in details with different examples

1. Stream map() method :

  • This Stream method is an intermediate operation which reads stream and returns new stream after applying given function
  • Function is a Functional Interface so either we can pass Function class or lambda expression
  • Function or lambda expression is applied to each of the elements in the Stream
  • Stream map() method is stateless which means it is non-interfering with other elements in the stream
  • Another intermediate operation can be applied to returned stream for example filter(), sorted(), distinct() methods can be applied after map() operation
  • map() method converts one set of values into another set of values applying given function
  • Note :- Number of elements returned in the new stream will always be equal to number of original elements
  • Method signature :- <R> Stream<R> map(Function<? super T, ? extends R> mapper)

2. Stream map() method examples :

2.1 To find square of all given numbers

  • A list contains first 10 natural numbers
  • We are applying function to find Square of all numbers using map() method i.e.; Lambda expression
  • Finally, printing to console using Stream forEach() method
package net.bench.resources.stream.map.example;

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

public class StreamMapMethod {

	public static void main(String[] args) {

		System.out.println("Square of first 10 natural numbers : \n");

		// Integer numbers
		List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

		// map function - to calculate Square
		Stream<Integer> stream = numbers.stream().map(i -> i*i);

		// print to console using forEach
		stream.forEach(System.out::println);
	}
}

Output:

Square of first 10 natural numbers : 

1
4
9
16
25
36
49
64
81
100

2.2 To convert all given Strings into upper case

  • A list contains few String values
  • We are applying function to convert all String present in the stream to upper case using map() method i.e.; Lambda expression
  • Finally, printing to console using Stream forEach() method
package net.bench.resources.stream.map.example;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

public class StreamMapMethodToUpperCase {

	public static void main(String[] args) {

		System.out.println("Converting String to Upper Case : \n");

		// List object
		List<String> names = new ArrayList<>();

		// add few String values
		names.add("Fidel");
		names.add("Abraham");
		names.add("Putin");
		names.add("Hitler");
		names.add("Robert");
		names.add("Amin");
		names.add("Napolean");

		// map function - to convert all String into upper case
		Stream<String> stream = names.stream().map(str -> str.toUpperCase());

		// print to console using forEach() method
		stream.forEach(str -> System.out.println(str));
	}
}

Output:

Converting String to Upper Case : 

FIDEL
ABRAHAM
PUTIN
HITLER
ROBERT
AMIN
NAPOLEAN

2.3 map and sorted for list of String values

  • A list contains few String values
  • First, we are applying function to convert all String present in the stream to upper case using map() method i.e.; Lambda expression
  • Then, sorting alphabetical order using sorted() method of Stream
  • Finally, printing to console using Stream forEach() method
package net.bench.resources.stream.map.example;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class StreamMapSortedMethod {

	public static void main(String[] args) {

		System.out.println("Upper Case and Sorting : \n");

		// List object
		List<String> names = new ArrayList<>();

		// add few String values
		names.add("Stars");
		names.add("Earth");
		names.add("Sky");
		names.add("Wind");
		names.add("Fire");
		names.add("Water");
		names.add("Moon");

		// map and sorted
		List<String> newList = names
				.stream() // 1. get stream
				.map(String::toUpperCase) // 2.1 upper case
				.sorted() // 2.2 sorting alphabetically
				.collect(Collectors.toList()); // 3. collecting to List

		// printing to console using forEach
		newList.forEach(name -> System.out.println(name));
	}
}

Output:

Upper Case and Sorting : 

EARTH
FIRE
MOON
SKY
STARS
WATER
WIND

2.4 map and filter() and collect() methods of Stream API

  • In this example, we are going to extract percentage details from List of Students using map() method
  • After extracting percentages, we are filtering only first class students whose percentage is greater than 60 using filter() method
  • Filtered Student’s percentage then collected into new List using collect() method
  • Finally, printing to console using Stream forEach() method
package net.bench.resources.stream.map.example;

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

class Student {

	// member variables
	String name;
	double percentage;
	String department;

	// public parameterized constructor
	public Student(String name, double percentage, String department) {
		super();
		this.name = name;
		this.percentage = percentage;
		this.department = department;
	}

	// getter and setter
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public double getPercentage() {
		return percentage;
	}

	public void setPercentage(double percentage) {
		this.percentage = percentage;
	}

	public String getDepartment() {
		return department;
	}

	public void setDepartment(String department) {
		this.department = department;
	}
}

public class StreamMapFilterMethod {

	public static void main(String[] args) {

		System.out.println("First class Student percentage : \n");

		List<Student> studentList = Arrays.asList(
				new Student("Vanita", 62, "Arts"),
				new Student("Rajesh", 55, "Commerce"),
				new Student("Naresh", 73, "Science"),
				new Student("Shiva", 64, "Arts"),
				new Student("Dinesh", 72, "Science"),
				new Student("Suresh", 50, "Commerce"),
				new Student("Radhika", 61, "Science")
				);

		// map and distinct
		List<Double> newList = studentList
				.stream() // 1. get stream
				.map(s -> s.getPercentage()) // 2.1 get percentage
				.filter(p -> p > 60) // 2.2 filter first class student
				.collect(Collectors.toList());

		// print to console
		newList.forEach(System.out::println);
	}
}

Output:

First class Student percentage : 

62.0
73.0
64.0
72.0
61.0

2.5 map() and distinct() from Student list

  • In this example, we are going to extract department details from List of Students using map() method
  • After extracting department, we are finding distinct departments using distinct() method
  • Finally, collecting distinct department into new List using collect() method and printing to console using Stream forEach() method
package net.bench.resources.stream.map.example;

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

class Student {

	// member variables
	String name;
	double percentage;
	String department;

	// public parameterized constructor
	public Student(String name, double percentage, String department) {
		super();
		this.name = name;
		this.percentage = percentage;
		this.department = department;
	}

	// getter and setter
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public double getPercentage() {
		return percentage;
	}

	public void setPercentage(double percentage) {
		this.percentage = percentage;
	}

	public String getDepartment() {
		return department;
	}

	public void setDepartment(String department) {
		this.department = department;
	}
}

public class StreamMapDistinctMethod {

	public static void main(String[] args) {

		System.out.println("Student - Distinct departments : \n");

		List<Student> studentList = Arrays.asList(
				new Student("Vanita", 62, "Arts"),
				new Student("Rajesh", 55, "Commerce"),
				new Student("Naresh", 73, "Science"),
				new Student("Shiva", 64, "Arts"),
				new Student("Dinesh", 72, "Science"),
				new Student("Suresh", 50, "Commerce"),
				new Student("Radhika", 61, "Science")
				);

		// map and distinct
		List<String> newList = studentList
				.stream() // 1. get stream
				.map(s -> s.getDepartment()) // 2.1 get departments
				.distinct() // 2.2 get distinct departments
				.collect(Collectors.toList());

		// print to console
		newList.forEach(System.out::println);
	}
}

Output:

Student - Distinct departments : 

Arts
Commerce
Science

References:

Happy Coding !!
Happy Learning !!

Java 8 - Stream flapMap() method with examples
Java 8 - Stream filter() method with examples