map() Function in Java With Examples

In this post we’ll see examples of map() function in Java Stream API that is used to apply some transformation to the elements in a stream. When you use a map operation a new stream is returned consisting of the resultant elements after applying the given function to the elements of source stream.

Generalized map() function in java.util.stream.Stream interface is-

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

Here R is the element type of the new interface.

mapper is a non-interfering, stateless function applied to each element, mapper is of type Function which is a functional interface and can be implemented as a lambda expression.

Apart from the generalized map() function there are also methods mapToInt(), mapToLong(), and mapToDouble() returning IntStream, LongStream and DoubleStream respectively which are specialized primitive type streams for these primitive data types.

In the primitive type streams there is also a mapToObj() method which Returns an object-valued Stream.

map() Java Stream examples

1- Converting each element in a Stream in upper case and collecting those elements in a List. For this requirement map() method can be used to apply upperCase functionality to all the elements of the stream and then collect the result of this transformation into a List using collect() method.

List<String> names = Stream.of("Jack", "Lisa", "Scott", "Nikita", "Tony")
			   .map(s -> s.toUpperCase())
			   .collect(Collectors.toList());	
names.forEach(System.out::println);

Output

JACK
LISA
SCOTT
NIKITA
TONY

2- Using map() method to get a new Stream having only the selected fields from the source stream. That way you can transform the stream to have elements of new type.

Let’s say there is an Employee class with name, dept, age fields and the source stream contains objects of type Employee. Requirement is to map name and dept fields to a new stream of EmpDept type.

class Employee {
  private String name;
  private String dept;
  private int salary;

  Employee(String name, String dept, int salary){
    this.name = name;
    this.dept = dept;
    this.salary = salary;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public int getSalary() {
    return salary;
  }
  public void setSalary(int salary) {
    this.salary = salary;
  }
  public String getDept() {
    return dept;
  }
  public void setDept(String dept) {
    this.dept = dept;
  }
}

class EmpDept {
  private String name;
  private String dept;
  EmpDept(String name, String dept){
    this.name = name;
    this.dept = dept;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public String getDept() {
    return dept;
  }
  public void setDept(String dept) {
    this.dept = dept;
  }
}

public class EmpStream {
  public static void main(String[] args) {
    List<Employee> employeeList = new ArrayList<>(); 

    employeeList.add(new Employee("Jack", "Finance", 5500)); 
    employeeList.add(new Employee("Lisa", "Finance", 5600)); 
    employeeList.add(new Employee("Scott", "Finance", 7000));
    employeeList.add(new Employee("Nikita", "IT", 4500));
    employeeList.add(new Employee("Tony", "IT", 8000)); 

    List<EmpDept> emp = employeeList.stream()
             .map(e -> new EmpDept(e.getName(), e.getDept()))
             .collect(Collectors.toList());
    emp.forEach(e -> System.out.println("Name- " + e.getName() + 
                        " Department- " + e.getDept()));
  }
}

Output

Name- Jack Department- Finance
Name- Lisa Department- Finance
Name- Scott Department- Finance
Name- Nikita Department- IT
Name- Tony Department- IT

3- map() with filter example– Using map method to get a new stream having employee names in finance department. Filter method is used to filter those employees not matching the given predicate.

List<String> emp = employeeList.stream()
				.filter(e -> e.getDept().equals("Finance"))
				.map(e -> e.getName())
				.collect(Collectors.toList());
							   
emp.forEach(System.out::println);

Output

Jack
Lisa
Scott

Java mapToInt() example

1- If you want to get the average of salaries for the employees, using mapToInt() method you can get an IntStream consisting of salaries and then apply average() method on that int stream.

List<Employee> employeeList = new ArrayList<>(); 

employeeList.add(new Employee("Jack", "Finance", 5500)); 
employeeList.add(new Employee("Lisa", "Finance", 5600)); 
employeeList.add(new Employee("Scott", "Finance", 7000));
employeeList.add(new Employee("Nikita", "IT", 4500));
employeeList.add(new Employee("Tony", "IT", 8000)); 

double avgSalary = employeeList.stream()
                               .mapToInt(e -> e.getSalary())
                               .average()
                               .getAsDouble();
							   
System.out.println("Average salary- " + avgSalary);

Output

Average salary- 6120.0

2- If you want to get the maximum salary, using mapToInt() method you can get an IntStream consisting of salaries and then apply max() method on that int stream.

List<Employee> employeeList = new ArrayList<>(); 

employeeList.add(new Employee("Jack", "Finance", 5500)); 
employeeList.add(new Employee("Lisa", "Finance", 5600)); 
employeeList.add(new Employee("Scott", "Finance", 7000));
employeeList.add(new Employee("Nikita", "IT", 4500));
employeeList.add(new Employee("Tony", "IT", 8000)); 

int maxSalary = employeeList.stream()
                            .mapToInt(e -> e.getSalary())
                            .max()
                            .getAsInt();
							   
System.out.println("Maximum salary- " + maxSalary);

Output

Maximum salary- 8000

Related Posts

That’s all for the topic map() Function in Java With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.