/** * Creates a {@link Collector} which can be used to group a stream into a multi map. * * @param supplier the factory for creating the result map * @param classifier the method used to extract the key from the elements * @param <K> the extracted key type of the map * @param <V> the value type of the incoming stream and outgoing map * @return a <tt>Collector</tt> to be used with {@link Stream#collect(java.util.stream.Collector)} */ public static <K, V> Collector<V, MultiMap<K, V>, MultiMap<K, V>> groupingBy(Supplier<MultiMap<K, V>> supplier, Function<V, K> classifier) { return Collector.of(supplier, (map, value) -> map.put(classifier.apply(value), value), (a, b) -> a.merge(b), Function.identity(), Collector.Characteristics.IDENTITY_FINISH); }
/** * Creates a {@link Collector} which can be used to group a stream into a multi map. * <p> * This method permits the classifier function to return multiple keys for a single element. The element will * be added for all returned keys. * * @param supplier the factory for creating the result map * @param classifier the method used to extract the keys from the elements * @param <K> the extracted key type of the map * @param <V> the value type of the incoming stream and outgoing map * @return a <tt>Collector</tt> to be used with {@link Stream#collect(java.util.stream.Collector)} */ public static <K, V> Collector<V, MultiMap<K, V>, MultiMap<K, V>> groupingByMultiple(Supplier<MultiMap<K, V>> supplier, Function<V, Collection<K>> classifier) { return Collector.of(supplier, (map, value) -> classifier.apply(value).forEach(key -> map.put(key, value)), (a, b) -> a.merge(b), Function.identity(), Collector.Characteristics.IDENTITY_FINISH); }
/** * Provides a {@link Collector} which can be used to collect a {@link Stream} of tuples into a {@link MultiMap}. * <p> * The type of <tt>MultiMap</tt> used can be determined by the <tt>supplier</tt>. So for example * {@code MultiMap::createOrdered} will create a map with ordered keys. * * @param supplier factory for generating the result map * @param <K> key type of the tuples being processed * @param <V> value type of the tuples being processed * @return a <tt>Collector</tt> which transforms a stream of tuples into a multi map */ public static <K, V> Collector<Tuple<K, V>, MultiMap<K, V>, MultiMap<K, V>> toMultiMap(Supplier<MultiMap<K, V>> supplier) { return Collector.of(supplier, (map, tuple) -> map.put(tuple.getFirst(), tuple.getSecond()), (a, b) -> a.merge(b), Function.identity(), Collector.Characteristics.IDENTITY_FINISH); }