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
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 super T, ? extends K> keyFunction,
Function super T, ? extends V> valueFunction,
Supplier extends ImmutableMultimap.Builder> 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 super T, ? extends K> keyFunction,
Function super T, ? extends V> valueFunction) {
return toImmutableMultimap(keyFunction, valueFunction, ImmutableMultimap::builder);
}
public static Collector> toImmutableListMultimap(
Function super T, ? extends K> keyFunction,
Function super T, ? extends V> valueFunction) {
return toImmutableMultimap(keyFunction, valueFunction, ImmutableListMultimap::builder);
}
public static Collector> toImmutableSetMultimap(
Function super T, ? extends K> keyFunction,
Function super T, ? extends V> valueFunction) {
return toImmutableMultimap(keyFunction, valueFunction, ImmutableSetMultimap::builder);
}