layout: section title: “MapElements” permalink: /documentation/transforms/java/elementwise/mapelements/ section_menu: section-menu/documentation.html

MapElements

Examples

Example 1: providing the mapping function using a SimpleFunction

PCollection<String> lines = Create.of("Hello World", "Beam is fun");
PCollection<Integer> lineLengths = lines.apply(MapElements.via(
    new SimpleFunction<String, Integer>() {
      @Override
      public Integer apply(String line) {
        return line.length();
      }
    });

Example 2: providing the mapping function using a SerializableFunction, which allows the use of Java 8 lambdas. Due to type erasure, you need to provide a hint indicating the desired return type.

PCollection<String> lines = Create.of("Hello World", "Beam is fun");
PCollection<Integer> lineLengths = lines.apply(MapElements
    .into(TypeDescriptors.integers())
    .via((String line) -> line.length()));

Related transforms

  • [FlatMapElements]({{ site.baseurl }}/documentation/transforms/java/elementwise/flatmapelements) behaves the same as Map, but for each input it may produce zero or more outputs.
  • [Filter]({{ site.baseurl }}/documentation/transforms/java/elementwise/filter) is useful if the function is just deciding whether to output an element or not.
  • [ParDo]({{ site.baseurl }}/documentation/transforms/java/elementwise/pardo) is the most general element-wise mapping operation, and includes other abilities such as multiple output collections and side-inputs.