Class CustomCollectors


  • public class CustomCollectors
    extends Object
    The purpose of this class is to fill gaps in the Java Collectors api by offering convenient ways to retrieve implementations of Collector.

    For example, to get a collector that accumulates elements into a map with predictable iteration order:

    
    
         Map<String, Person> idToPerson =
             persons.stream().collect(toLinkedMap(Person::id, Functions.identity());
     
    Author:
    gjoranv
    • Method Detail

      • toLinkedMap

        public static <T,​K,​U> Collector<T,​?,​Map<K,​U>> toLinkedMap​(Function<? super T,​? extends K> keyMapper,
                                                                                                Function<? super T,​? extends U> valueMapper)
        Returns a Collector that accumulates elements into a Map that provides insertion order iteration. This a convenience that can be used instead of calling Collectors.toMap(Function, Function, BinaryOperator, Supplier). with a merger that throws upon duplicate keys.
        Type Parameters:
        T - Type of the input elements.
        K - Output type of the key mapping function.
        U - Output type of the value mapping function.
        Parameters:
        keyMapper - Mapping function to produce keys.
        valueMapper - Mapping function to produce values.
        Returns:
        A collector which collects elements into a map with insertion order iteration.
        Throws:
        CustomCollectors.DuplicateKeyException - If two elements map to the same key.
      • toCustomMap

        public static <T,​K,​U,​M extends Map<K,​U>> Collector<T,​?,​M> toCustomMap​(Function<? super T,​? extends K> keyMapper,
                                                                                                                  Function<? super T,​? extends U> valueMapper,
                                                                                                                  Supplier<M> mapSupplier)
        Returns a Collector that accumulates elements into a Map created by the given supplier. This a convenience that can be used instead of calling Collectors.toMap(Function, Function, BinaryOperator, Supplier). with a merger that throws upon duplicate keys.
        Type Parameters:
        T - Type of the input elements.
        K - Output type of the key mapping function.
        U - Output type of the value mapping function.
        M - Type of the resulting map.
        Parameters:
        keyMapper - Mapping function to produce keys.
        valueMapper - Mapping function to produce values.
        mapSupplier - Supplier of a new map.
        Returns:
        A collector which collects elements into a map created by the given supplier.
        Throws:
        CustomCollectors.DuplicateKeyException - If two elements map to the same key.