Stream map() operation with examples

Stream map()

Stream map() method is useful to map or transform an input collection into a new output collection.

For example, mapping numeric values to the squares of the numeric values or mapping characters to their uppercase equivalent etc.

stream map operation

map() is one of the most commonly used Stream operations.

The map() method ensures that the new stream has the same number of elements as the original stream. However, element types in the input don’t have to match the element types in the output collection.

The lambda expression passed in to the map() must be an instance of functional interface Function.

 

Stream map() examples

Here are some examples of Stream map operation.

Example : Converting Strings to uppercase equivalent using map

package com.topjavatutorial.java8examples;
 
import java.util.Arrays;
import java.util.List;
 
public class StreamOperations {
 
    public static void main(String[] args) {
        
        List<String> countries = Arrays.asList("Australia","Brazil", "China","Denmark","England","France","Germany");
        
        
        countries.stream().map(name -> name.toUpperCase())
                            .forEach(System.out::println);
        
 
    }
 
}

Output:

AUSTRALIA
BRAZIL
CHINA
DENMARK
ENGLAND
FRANCE
GERMANY

We could also use the String::toUpperCase method-reference to write the map() operation as follows:

countries.stream().map(String::toUpperCase)
        .forEach(System.out::println);

 

Example : Count number of letter in each String using Stream map()

The element types in the input don’t have to match the element types in the output collection. Here, input is a String and output is length of the String.

package com.topjavatutorial.java8examples;

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

public class StreamOperations {

  public static void main(String[] args) {
    List<String> countries = Arrays.asList("Germany", "England", "China",
        "Denmark", "Brazil", "France", "Australia");

    countries.stream().map(String::length)
        .forEach(System.out::println);

  }

}

Output:

7
7
5
7
6
6
9

 

map() vs forEach() method

The forEach() method simply runs the provided code for each element in the collection.

Similar to forEach(), the map() method iterates for each element in the collection. While iterating, it gathers the results of running the lambda expression provided for each element and provides the output collection.
 

map() vs filter() method

Similar to map() method, filter() also returns an iterator.

However, the map() method returns a collection of same size as the input. filter() method returns a collection that is subset of the input collection.
 

You may also like :

Java 8 new features

Java 8 Streams

 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags