org.molgenis.util.stream.MultimapCollectors Maven / Gradle / Ivy
package org.molgenis.util.stream;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
import java.util.stream.Collectors;
/**
* Collectors that collect to {@link Multimap}.
*
* see {@link Collectors#toMap(Function, Function)}, the equivalent of which is not (yet?)
* present in guava for the {@link Multimap}.
*/
public class MultimapCollectors {
private MultimapCollectors() {}
public static
Collector, ArrayListMultimap> toArrayListMultimap(
Function keyGenerator, Function valueGenerator) {
return toMultimap(ArrayListMultimap::create, keyGenerator, valueGenerator);
}
public static , E> Collector toMultimap(
Supplier supplier, Function keyGenerator, Function valueGenerator) {
return Collector.of(
supplier,
(map, entry) -> map.put(keyGenerator.apply(entry), valueGenerator.apply(entry)),
(map1, map2) -> {
map1.putAll(map2);
return map1;
});
}
}