0

As we know, Java Stream groupingBy doesn't allow null keys. And there is a solution for that case, which allows to group by null keys:

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

But groupingBy has also a signature, which allows to pass not only function, but also an another Collector:

public static <T, K, A, D>
    Collector<T, ?, Map<K, D>> groupingBy(Function<? super T, ? extends K> classifier,
                                          Collector<? super T, A, D> downstream)

How should I allow null keys in that case?

Nowhere Man
  • 18,291
  • 9
  • 17
  • 38

0 Answers0