3

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.

Naman
  • 27,789
  • 26
  • 218
  • 353

1 Answers1

2

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);
  }
}
Slaw
  • 37,820
  • 8
  • 53
  • 80
  • Oh that's what I meant by extend = add my own. But yeah, this works. Thank you! – David Woodworth Jan 17 '20 at 20:46
  • What makes this a factory method? – jaco0646 Jan 18 '20 at 04:39
  • @jaco0646 Could be the wrong term. What would you call it? Utility method? – Slaw Jan 18 '20 at 18:22
  • Yeah, I think _utility method_ is accurate here. – jaco0646 Jan 20 '20 at 17:06
  • @jaco0646 Edited my answer. Though I still think it has at least some characteristics of a _factory method_. – Slaw Jan 20 '20 at 17:47
  • You may be interested in [What are the differences between Abstract Factory and Factory Method patterns?](https://stackoverflow.com/questions/5739611/what-are-the-differences-between-abstract-factory-and-factory-design-patterns/50786084#50786084) I've spent too much time thinking about factories. – jaco0646 Jan 20 '20 at 18:08