Collectors.groupingBy doesn't accept null keys

前端 未结 6 2063
囚心锁ツ
囚心锁ツ 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:19

    First of all, you are using lots of raw objects. This is not a good idea at all, first convert the following:

    • Class to Class, ie. instead of a raw type, a parametrized type with an unknown class.
    • Instead of forcefully casting to a HashMap, you should supply a HashMap to the collector.

    First the correctly typed code, without caring about a NPE yet:

    Stream> stream = Stream.of(ArrayList.class);
    HashMap, List>> hashMap = (HashMap, List>>)stream
            .collect(Collectors.groupingBy(Class::getSuperclass));
    

    Now we get rid of the forceful cast there, and instead do it correctly:

    Stream> stream = Stream.of(ArrayList.class);
    HashMap, List>> hashMap = stream
            .collect(Collectors.groupingBy(
                    Class::getSuperclass,
                    HashMap::new,
                    Collectors.toList()
            ));
    

    Here we replace the groupingBy which just takes a classifier, to one that takes a classifier, a supplier and a collector. Essentially this is the same as what there was before, but now it is correctly typed.

    You are indeed correct that in the javadoc it is not stated that it will throw a NPE, and I do not think it should be throwing one, as I am allowed to supply whatever map I want, and if my map allows null keys, then it should be allowed.

    I do not see any other way to do it simpler as of now, I'll try to look more into it.

提交回复
热议问题