对于第一个问题,我同意skiwi的观点,即它不应该抛出
NPE。我希望他们能够对此进行更改(或者至少将其添加到javadoc中)。同时,为了回答第二个问题,我决定使用
Collectors.toMap代替
Collectors.groupingBy:
Stream<Class<?>> stream = Stream.of(ArrayList.class);Map<Class<?>, List<Class<?>>> map = stream.collect( Collectors.toMap( Class::getSuperclass, Collections::singletonList, (List<Class<?>> oldList, List<Class<?>> newEl) -> { List<Class<?>> newList = new ArrayList<>(oldList.size() + 1); newList.addAll(oldList); newList.addAll(newEl); return newList; }));或者,将其封装:
public static <T, A> Collector<T, ?, Map<A, List<T>>>groupingBy_WithNullKeys(Function<? super T, ? extends A> classifier) { return Collectors.toMap( classifier, Collections::singletonList, (List<T> oldList, List<T> newEl) -> { List<T> newList = new ArrayList<>(oldList.size() + 1); newList.addAll(oldList); newList.addAll(newEl); return newList; }); }并像这样使用它:
Stream<Class<?>> stream = Stream.of(ArrayList.class);Map<Class<?>, List<Class<?>>> map = stream.collect(groupingBy_WithNullKeys(Class::getSuperclass));
请注意,rolfl给出了另一个更复杂的答案,该答案使您可以指定自己的地图和列表供应商。我还没有测试。



