org.molgenis.util.stream.MapCollectors Maven / Gradle / Ivy
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 super T, ? extends K> keyMapper, Function super T, ? extends U> 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