Collectors.groupingBy doesn't accept null keys

前端 未结 6 2054
囚心锁ツ
囚心锁ツ 2020-12-15 02:49

In Java 8, this works:

Stream stream = Stream.of(ArrayList.class);
HashMap> map = (HashMap)stream.collect(Collect         


        
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-15 03:21

    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 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.

提交回复
热议问题