Java 8 Stream map

Filed Under: Java

Java 8 Stream map function can be used to perform some operation on all of it’s elements. Java Stream map is an intermediate operation, so it returns Stream.

Java 8 Stream Map

java 8 stream map, java stream map example

Below is the map method declared in Java 8 Stream interface.


<R> Stream<R> map(Function<? super T, ? extends R> mapper);

Stream map method takes Function as argument that is a functional interface.

Let’s now look at some example where stream map method become useful.

Java Stream map example

Let’s assume we have a list of names and we want to find which of them are present in some Oracle database table. Now since Oracle is case sensitive, we can convert list of string to upper case and then at the database side we can use to_upper method with SQL query.

Usually before java 8, we can do it using for loop as shown below.


List<String> names = Arrays.asList("Pankaj", "amit", "DAVID");

List<String> upperCaseNames = new ArrayList<>();
for (String n : names) {
	upperCaseNames.add(n.toUpperCase());
}
// now send upperCaseNames for processing

We can do the same thing using java stream map function as shown below in a single line.


upperCaseNames = names.stream().map(t -> t.toUpperCase()).collect(Collectors.toList());

We can also write it like below.


upperCaseNames = names.stream().map(String::toUpperCase).collect(Collectors.toList());

Java Stream map example with objects

Now let’s look at more practical example of Stream map usage. We have an Emp class as below.


package com.journaldev.examples;

public class Emp {

	private int id;
	private String name;
	private long salary;
	private String designation;

	public Emp(int i, String n, long s, String d) {
		this.id = i;
		this.name = n;
		this.salary = s;
		this.designation = d;
	}

	@Override
	public String toString(){
		return id+name+salary+designation;
	}
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

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

	public long getSalary() {
		return salary;
	}

	public void setSalary(long salary) {
		this.salary = salary;
	}

	public String getDesignation() {
		return designation;
	}

	public void setDesignation(String designation) {
		this.designation = designation;
	}

}

We have a method to get all the employees data. Now we want to pass employees data to HR system but we don’t want to disclose the salary. So we will have to use below code to process each employee and remove their salary.


List<Emp> empForHR = new ArrayList<>();
	for(Emp e : allEmpList){
		Emp temp = new Emp(e.getId(),e.getName(),e.getSalary(),e.getDesignation());
		temp.setSalary(0);
		empForHR.add(temp);
	}

Now using java 8 stream map function, we can do the same thing like below.


empForHR = allEmpList.stream().map(e -> {
		e.setSalary(0L);
		return e;
	}).collect(Collectors.toList());

Below is the final program for java stream map example with object transformation.


package com.journaldev.examples;

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

public class JavaStreamMapExample {

	public static void main(String[] args) {

		List<Emp> allEmpList = getAllEmps();
		System.out.println(allEmpList);
		
		List<Emp> empForHR = new ArrayList<>();
		for(Emp e : allEmpList){
			Emp temp = new Emp(e.getId(),e.getName(),e.getSalary(),e.getDesignation());
			temp.setSalary(0);
			empForHR.add(temp);
		}
		System.out.println(empForHR);
		
		empForHR = allEmpList.stream().map(e -> {
			e.setSalary(0L);
			return e;
		}).collect(Collectors.toList());
		System.out.println(empForHR);
	}

	private static List<Emp> getAllEmps() {
		List<Emp> el = new ArrayList<>();
		Emp e1 = new Emp(1, "Pankaj", 100L, "SE");
		el.add(e1);
		Emp e2 = new Emp(2, "David", 200L, "QE");
		el.add(e2);
		Emp e3 = new Emp(3, "Lisa", 300L, "CEO");
		el.add(e3);
		return el;
	}

}

When we run the above program, we get below output.


[1Pankaj100SE, 2David200QE, 3Lisa300CEO]
[1Pankaj0SE, 2David0QE, 3Lisa0CEO]
[1Pankaj0SE, 2David0QE, 3Lisa0CEO]

We can also convert the Emp object to some other object in the map method Function implementation.

That’s all for java 8 stream map examples.

Reference: Official JavaDoc

Comments

  1. Exactly what I’ve been looking for! Thanks for sharing this handy information.

  2. Bharath says:

    Very Nice aritical.

  3. Sangeetha says:

    Nice artical. The same can be achieved using stream foreach method. Is there any difference using map instead of foreach.

  4. Albert Trotter says:

    i am facing error in line List empForHR = new ArrayList();..can any one help????

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages