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.

1 Answer 1

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);
  }
}
Sign up to request clarification or add additional context in comments.

6 Comments

Oh that's what I meant by extend = add my own. But yeah, this works. Thank you!
What makes this a factory method?
@jaco0646 Could be the wrong term. What would you call it? Utility method?
Yeah, I think utility method is accurate here.
@jaco0646 Edited my answer. Though I still think it has at least some characteristics of a factory method.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.