java collectors mapping

java collectors mapping

In Java, the Collectors class is a utility class that provides a number of static methods for creating common types of collectors. A collector is an object that accumulates input elements and produces a final result.

One of the methods provided by the Collectors class is mapping, which takes a function as an argument and returns a collector that applies the function to the input elements and adds the results to the resulting collection.

Here is an example of how to use the Collectors.mapping method to apply a function to the elements of a stream and collect the results in a List:

refer to:‮iruttual‬.com
import java.util.List;
import java.util.stream.Collectors;

public class Main {
  public static void main(String[] args) {
    List<String> strings = List.of("apple", "banana", "cherry");

    List<Integer> lengths = strings.stream()
        .collect(Collectors.mapping(String::length, Collectors.toList()));

    // Output: [5, 6, 6]
    System.out.println(lengths);
  }
}

In this example, a List of strings is created and a stream is created from it using the stream method. The Collectors.mapping method is used to apply the length method of the String class to each element of the stream, and the Collectors.toList method is used to collect the results in a List. The resulting List contains the lengths of the strings in the original list.

Created Time:2017-11-03 00:14:51  Author:lautturi