map() Method Example In Java 8 Stream

The stream map() method is an intermediate operation. This method transforms elements of a stream by applying a mapping function to each of the elements and returns a new stream. It accepts a Function mapper object as an argument. This function describes how each element in the original stream is transformed into an element in the new stream.

  1. Stream map(Function mapper) is an intermediate operation.
  2. Stream map() method accepts a Function mapper object in argument.
  3. Stream map() method is used to transform elements of a stream by applying a mapping function to each of the elements.
  4. Stream map() method returnes a new stream.

Syntax:

 Stream map(Function mapper)

Example of stream map method with collect method

//Importing required classes
import java.util.*;
import java.io.*;
import java.util.stream.*;

public class StreamMapExample {
   public static void main (String args[]){ 
   Integer[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
   //Filtering the even numbers from a collection
   List<Integer> evenList = 
   Arrays.asList(numbers).stream() 
        //passing lambda expression in argument
        .filter(i -> i % 2 == 0)
        //multiplying by 2 for each element after filter
        .map(i -> i*2)
        .collect(Collectors.toList());
               
  System.out.println("Filtered even numbers : "+ evenList);
 }
}


Output:
    Filtered even numbers : [4, 8, 12, 16, 20, 24]

Example of stream map method with forEach method

//Importing required classes
import java.util.*;
import java.io.*;
import java.util.stream.*;

public class StreamMapExample {
  public static void main (String args[]){ 
  Integer[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
  //Filtering the even numbers from a collection
  Arrays.asList(numbers).stream()
        //passing lambda expression in argument
        .filter(i -> i % 2 == 0)
        //multiplying by 3 for each element after filter
        .map(i -> i*3)
        //forEach with method reference
        .forEach(System.out::println);    
  }
}

Output:
    6
    12
    18
    24
    30
    36