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

WithKeys

There are two versions of WithKeys, depending on how the key should be determined:

  • WithKeys.of(SerializableFunction<V, K> fn) takes a function to compute the key from each value.
  • WithKeys.of(K key) associates each value with the specified key.

Examples

Example

PCollection<String> words = Create.of("Hello", "World", "Beam", "is", "fun");
PCollection<KV<Integer, String>> lengthAndWord =
  words.apply(WithKeys.of(new SerialiazableFunction<String, Integer>() {
    @Override
    public Integer apply(String s) {
      return s.length();
    }
  });

Related transforms

  • [Keys]({{ site.baseurl }}/documentation/transforms/java/elementwise/keys) for extracting the key of each component.
  • [Values]({{ site.baseurl }}/documentation/transforms/java/elementwise/values) for extracting the value of each element.
  • [KvSwap]({{ site.baseurl }}/documentation/transforms/java/elementwise/kvswap) swaps key-value pair values.