Learnitweb

Java 8 stream map() and example

This method is used when you want to process elements of a stream and apply some function on each element of a stream.

We usually use map() while processing collection elements. An example to explain the use of map() is to write a program to multiply each element of a list of integers by 2.

Signature of this method is:

<R> Stream<R>	map(Function<? super T,? extends R> mapper)
  • Here, R is the element type of the generated stream. mapper is a stateless function which is applied to each element of the stream to generate a new stream.
  • map() method returns a stream consisting of the results of applying the given function to the elements of this stream.
  • This method is an intermediate operation and is lazy in nature. That is, this method instead of returning a result will return a stream and will not be executed until a terminal operation is called.
  • There are similar methods to map() which return DoubleStream, IntStream and LongStream. These methods are specialized methods for double, int and long values as the mapper functions produce a double/int/long valued result respectively.
  • Signature of these methods are:
    • DoubleStream mapToDouble(ToDoubleFunction mapper)
    • IntStream mapToInt(ToIntFunction mapper)
    • LongStream mapToLong(ToLongFunction mapper)

Now, we’ll see how we can use map() with the help of few examples.

Java example to find square of each element in the list

import java.util.Arrays;
import java.util.List;

/*Java program to find square(n*n)
of elements of list*/ 
public class StreamMapExample {
    public static void main(String[] args) {
        //Create list of integers
    	List<Integer> list = Arrays.asList(2, 3, 4, 5);
        
    	//Use map() method to calculate square of elements
        // and print the result
        list.stream().map(element -> element * element).forEach(System.out::println);
    }
}

Output

4
9
16
25

Java program to map length of string with String

This program finds length of strings in a list using map() method.

import java.util.Arrays;
import java.util.List;

/*Java program to find square(n*n)
of elements of list*/ 
public class StreamMapExample {
    public static void main(String[] args) {
    	// Creating a list of Strings 
    	List<String> list = Arrays.asList("apple", "boy", "elephant"); 

    	// Using Stream map() to get length of each String
    	//and display on console
    	list.stream().map(str -> str.length()).forEach(System.out::println); 
    }
}

Output

5
3
8