Vì tôi chưa tìm thấy một thư viện thu thập như vậy, tôi đang chia sẻ vết nứt đầu tiên của mình tại một nơi cụ thể mà tôi cần. Không có chuông hay còi ở đây! (Chẳng hạn như xử lý hoặc hợp nhất các khóa trùng lặp.)
Vui lòng đề xuất cải tiến.
/**
* 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();
}
};
}
Nguồn
2015-12-29 06:49:49
Tôi rất ngạc nhiên khi bạn không thấy bất cứ điều gì trên internet. Tìm kiếm "guava java 8 collector" trong một công cụ tìm kiếm phổ biến trả về rất nhiều mã có thể sử dụng trực tiếp, bao gồm các kết quả trực tiếp trong các dự án ổi (như các vấn đề). –
Chúng tôi cung cấp 'collectionsAndThen()' cho mục đích này. –
Các câu trả lời trong câu hỏi trên 'ImmutableMultimap' thực sự trả lời các câu hỏi trước mắt của tôi. Tuy nhiên không có giải pháp nào ở đó hoặc bây giờ tôi tìm thấy trên web dường như chứa một tập hợp các hàm hoàn chỉnh để xử lý 'ImmutableMap' - chúng thiếu khả năng hợp nhất-khóa-phím và/hoặc không ném' IllegalStateException' (theo quy ước được thiết lập bởi 'Người sưu tầm') –