In Java 8, this works:
Stream stream = Stream.of(ArrayList.class);
HashMap> map = (HashMap)stream.collect(Collect
For the first question, I agree with skiwi that it shouldn't be throwing a NPE
. I hope they will change that (or else at least add it to the javadoc). Meanwhile, to answer the second question I decided to use Collectors.toMap
instead of Collectors.groupingBy
:
Stream> stream = Stream.of(ArrayList.class);
Map, List>> map = stream.collect(
Collectors.toMap(
Class::getSuperclass,
Collections::singletonList,
(List> oldList, List> newEl) -> {
List> newList = new ArrayList<>(oldList.size() + 1);
newList.addAll(oldList);
newList.addAll(newEl);
return newList;
}));
Or, encapsulating it:
/** Like Collectors.groupingBy, but accepts null keys. */
public static Collector>>
groupingBy_WithNullKeys(Function super T, ? extends A> classifier) {
return Collectors.toMap(
classifier,
Collections::singletonList,
(List oldList, List newEl) -> {
List newList = new ArrayList<>(oldList.size() + 1);
newList.addAll(oldList);
newList.addAll(newEl);
return newList;
});
}
And use it like this:
Stream> stream = Stream.of(ArrayList.class);
Map, List>> map = stream.collect(groupingBy_WithNullKeys(Class::getSuperclass));
Please note rolfl gave another, more complicated answer, which allows you to specify your own Map and List supplier. I haven't tested it.