私はコレクターのようなライブラリを見つけられませんでした、まだ、私は私が必要としました特定のもので私の最初の亀裂を共有していますので。ここに鐘や笛はありません! (このような取り扱いとして、あるいは重複したキーをマージする。)
改善を提案すること自由に感じなさい。
/**
* A variant of {@link Collectors#toMap(Function, Function)} for immutable maps.
* <p>
* Note this variant throws {@link IllegalArgumentException} upon duplicate keys, rather than
* {@link IllegalStateException}
*
* @param <T> type of the input elements
* @param <K> output type of the key mapping function
* @param <V> output type of the value mapping function
* @param keyMapper a mapping function to produce keys
* @param valueMapper a mapping function to produce values
*
* @return a {@code Collector} which collects elements into a {@code Map} whose keys and values
* are the result of applying mapping functions to the input elements
*
* @throws IllegalArgumentException upon duplicate keys
*/
public static <T, K, V> Collector<T, ?, ImmutableMap<K,V>> toImmutableMap(
Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends V> valueMapper) {
return new Collector<T, ImmutableMap.Builder<K,V>, ImmutableMap<K,V>>() {
public Supplier<Builder<K, V>> supplier() {
return ImmutableMap.Builder::new;
}
public BiConsumer<Builder<K, V>, T> accumulator() {
return (builder, element) -> {
K key = keyMapper.apply(element);
V value = valueMapper.apply(element);
builder.put(key, value);
};
}
public BinaryOperator<Builder<K, V>> combiner() {
return (b1, b2) -> {
b1.putAll(b2.build());
return b1;
};
}
public Function<Builder<K, V>, ImmutableMap<K, V>> finisher() {
return builder -> builder.build();
}
public Set<Collector.Characteristics> characteristics() {
return ImmutableSet.of();
}
};
}
私はあなたがインターネット上で何かを見なかったことに驚いています。一般的な検索エンジンで "guava java 8 collector"を検索すると、直接Guavaプロジェクト(結果として)の結果を含む多くの直接使用可能なコードが返されます。 –
この目的で 'collectingAndThen()'を提供しました。 –
'ImmutableMultimap'の質問の回答は、私の直接の質問に本当に答えています。しかし、そこにある解決策や私が今Web上で見つけた解決策のどれも 'ImmutableMap'を扱うための完璧な関数群を含んでいないようです - 彼らは複製キーをマージする能力がなく、かつ/または' IllegalStateException'を投げない(コレクターによって設定された規約に従います) –