被接受的答案包含与默认合并器(抛出异常)不同的合并器。很遗憾,在Java的Collectors
类中不存在三个参数的toMap(keyFunction, valueFunction, mapFactory)
重载。由于我只需要LinkedHashMap
,所以我从该类的内部复制粘贴了必要的部分,并将其作为自定义辅助方法进行了编写。行为与两个参数的toMap
相同,除了生成的映射是LinkedHashMap
。
class Helper {
private static <K,V,M extends Map<K,V>> BinaryOperator<M> uniqKeysMapMerger() {
return (m1, m2) -> {
for (Map.Entry<K,V> e : m2.entrySet()) {
K k = e.getKey();
V v = Objects.requireNonNull(e.getValue());
V u = m1.putIfAbsent(k, v);
if (u != null) throw new IllegalStateException(String.format("Duplicate key %s (attempted merging values %s and %s)", k, u, v));
}
return m1;
};
}
private static <T,K,V> BiConsumer<Map<K,V>,T> uniqKeysMapAccumulator(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends V> valueMapper) {
return (map, element) -> {
K k = keyMapper.apply(element);
V v = Objects.requireNonNull(valueMapper.apply(element));
V u = map.putIfAbsent(k, v);
if (u != null) throw new IllegalStateException(String.format("Duplicate key %s (attempted merging values %s and %s)", k, u, v));
};
}
public static <T,K,U> Collector<T,?,Map<K,U>> toLinkedHashMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper) {
return Collector.of(LinkedHashMap::new, uniqKeysMapAccumulator(keyMapper, valueMapper), uniqKeysMapMerger());
}
}
LinkedHashMap<String, Object> resources
。 - xtra