Java 8 Stream map method Example

7 years ago Lalit Bhagtani 0

In this tutorial, we will learn about Java 8 stream map method.

Java 8 Stream map

map() method :-

This method takes one Function as an argument and returns a new stream consisting of the results generated by applying the passed function to all the elements of the stream.

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

Reference :-  map() method JavaDocs

Java 8 Stream map

Problem Statement :-

Given a list of integers, create a new list whose elements are square of given list elements.

Java 7 :- To implement this, iterate through the list of integers and add square of each element to the newly created List object.

  public static void main(String[] args){
 
    List<Integer> intList = Arrays.asList(1, 2, 3, 4, 5);
 
    List<Integer> newList = new ArrayList<Integer>();
 
    for(Integer num:intList){
      newList.add(num*num);
    }
 
    System.out.println(newList.toString());
  }

Java 8 Stream map :- Implementation using stream API.

  public static void main(String[] args){
 
    List<Integer> intList = Arrays.asList(1, 2, 3, 4, 5);
 
    List<Integer> newList = intList.stream().map( e -> e * e ).collect(Collectors.toList());
 
    System.out.println(newList);
  }  

Result :- 

[1, 4, 9, 16, 25]

Java 8 Stream API provide us three variation of map method, which can be used in case of int, long and double. They are as follows:-

  1. IntStream mapToInt ( ToIntFunction<? super T> mapper ) :- This method takes one ToIntFunction as an argument and returns a new IntStream consisting of the results generated by applying the passed function to all the elements of the stream.
  2. LongStream mapToLong ( ToLongFunction<? super T> mapper ) :- This method takes one ToLongFunction as an argument and returns a new LongStream consisting of the results generated by applying the passed function to all the elements of the stream.
  3. DoubleStream mapToDouble ( ToDoubleFunction<? super T> mapper ) :- This method takes one ToDoubleFunction as an argument and returns a new DoubleStream consisting of the results generated by applying the passed function to all the elements of the stream.

That’s all for Java 8 Stream map method. If you liked it, please share your thoughts in comments section and share it with others too.