Java 8 Collectors.toMap SortedMap

2022-08-31 12:37:36

我正在使用Java 8 lambdas,并希望使用返回.我能想到的最好的方法是用假人调用以下方法,并等于.CollectorstoMapSortedMapCollectorstoMapmergeFunctionmapSupplierTreeMap::new

public static <T, K, U, M extends Map<K, U>>
        Collector<T, ?, M> toMap(Function<? super T, ? extends K> keyMapper,
                Function<? super T, ? extends U> valueMapper,
                BinaryOperator<U> mergeFunction,
                Supplier<M> mapSupplier) {
    BiConsumer<M, T> accumulator = (map, element) -> map.merge(keyMapper.apply(element),
            valueMapper.apply(element), mergeFunction);
    return new CollectorImpl<>(mapSupplier, accumulator, mapMerger(mergeFunction), CH_ID);
}

我不想像我想要的那样传递合并函数,就像基本实现一样,如下所示:throwingMerger()toMap

public static <T, K, U>
        Collector<T, ?, Map<K, U>> toMap(Function<? super T, ? extends K> keyMapper,
                Function<? super T, ? extends U> valueMapper) {
    return toMap(keyMapper, valueMapper, throwingMerger(), HashMap::new);
}

使用返回 ?CollectorsSortedMap


答案 1

我不认为你能得到比这更好的:

.collect(Collectors.toMap(keyMapper, valueMapper,
                        (v1,v2) ->{ throw new RuntimeException(String.format("Duplicate key for values %s and %s", v1, v2));},
                        TreeMap::new));

其中lambda与lambda相同,但我不能直接调用它,因为它是包私有的(当然,您始终可以为此创建自己的静态方法。throwthrowingMerger()throwingMerger()


答案 2

基于 dkatzel 确认没有一个好的 API 方法,我选择维护我自己的自定义收集器类:

public final class StackOverflowExampleCollectors {

    private StackOverflowExampleCollectors() {
        throw new UnsupportedOperationException();
    }

    private static <T> BinaryOperator<T> throwingMerger() {
        return (u, v) -> {
            throw new IllegalStateException(String.format("Duplicate key %s", u));
        };
    }

    public static <T, K, U, M extends Map<K, U>> Collector<T, ?, M> toMap(Function<? super T, ? extends K> keyMapper,
            Function<? super T, ? extends U> valueMapper, Supplier<M> mapSupplier) {
        return Collectors.toMap(keyMapper, valueMapper, throwingMerger(), mapSupplier);
    }

}

推荐