Java 8 collector for Guava immutable collections?

前端 未结 5 2237
花落未央
花落未央 2020-12-17 09:55

I really like Java 8 streams and Guava\'s immutable collections, but I can\'t figure out how to use the two together.

For example, how do I implement a Java 8 Collec

5条回答
  •  星月不相逢
    2020-12-17 10:00

    Here's a version that will support several ImmutableMultimap implementations. Note that the first method is private since it requires an unsafe cast.

    @SuppressWarnings("unchecked")
    private static > Collector toImmutableMultimap(
            Function keyFunction,
            Function valueFunction,
            Supplier> builderSupplier) {
    
        return Collector.of(
                builderSupplier,
                (builder, element) -> builder.put(keyFunction.apply(element), valueFunction.apply(element)),
                (left, right) -> {
                    left.putAll(right.build());
                    return left;
                },
                builder -> (M)builder.build());
    }
    
    public static  Collector> toImmutableMultimap(
            Function keyFunction,
            Function valueFunction) {
        return toImmutableMultimap(keyFunction, valueFunction, ImmutableMultimap::builder);
    }
    
    public static  Collector> toImmutableListMultimap(
            Function keyFunction,
            Function valueFunction) {
        return toImmutableMultimap(keyFunction, valueFunction, ImmutableListMultimap::builder);
    }
    
    public static  Collector> toImmutableSetMultimap(
            Function keyFunction,
            Function valueFunction) {
        return toImmutableMultimap(keyFunction, valueFunction, ImmutableSetMultimap::builder);
    }
    

提交回复
热议问题