Search code examples
javajava-streamcollectors

Java Streams: Extend Built-In Collector


I would like to know if it is possible to extend a built-in Java Stream collector from, the java.util.stream.Collectors class, as opposed to building a custom collector, from scratch, and therefore duplicating code already implemented in that class.

For example: Let's say I have Stream<Map.Entry<String, Long>> mapEntryStreamand I want to collect that to a map of type Map<String, Long>.

Of course I could do:

mapEntryStream.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

But let's say I would like keys and entries inferred like so:

//Not a real Java Collectors method
mapEntryStream.collect(Collectors.toMap());

So how do I make a collector, like the one above, that takes no arguments but invokes Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)?

Please note: This is not a question about whether such a collector ought to be made - only if it can be made.


Solution

  • You can't add a method to the Collectors class. However, you could create your own utility method that returns what you want:

    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.stream.Collector;
    import java.util.stream.Collectors;
    
    public class MoreCollectors {
    
      public static <K, V> Collector<Entry<K, V>, ?, Map<K, V>> entriesToMap() {
        return Collectors.toMap(Entry::getKey, Entry::getValue);
      }
    }