All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.molgenis.util.stream.MapCollectors Maven / Gradle / Ivy

There is a newer version: 8.4.5
Show newest version
package org.molgenis.util.stream;

import static java.lang.String.format;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * Collectors that collect to {@link Map}.
 *
 * @see Collectors
 */
public class MapCollectors {
  private MapCollectors() {}

  /**
   * Based on https://stackoverflow.com/a/29090335/8579801
   */
  @SuppressWarnings("java:S1452")
  public static  Collector> toLinkedMap(
      Function keyMapper, Function valueMapper) {
    return Collectors.toMap(keyMapper, valueMapper, throwingMerger(), LinkedHashMap::new);
  }

  private static  BinaryOperator throwingMerger() {
    return (u, v) -> {
      throw new IllegalStateException(
          format("Duplicate key detected with values '%s' and '%s'", u, v));
    };
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy