Java Stream How to - Use method reference in map








Question

We would like to know how to use method reference in map.

Answer

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
// www.  jav  a 2  s  .c  om
public class Main {

  public static void main(String[] args) throws Exception{
    // map
    List<String> words = Arrays.asList("Hello", "World");
    List<Integer> wordLengths = words.stream()
                                     .map(String::length)
                                     .collect(Collectors.toList());
    System.out.println(wordLengths);


  }

}

The code above generates the following result.