简体   繁体   中英

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>> mapEntryStream and 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.

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);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM