Collectors.groupingBy不能以null为key进行分组的解决方案

增加如下方法,使用该方法进行替换即可

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

具体使用

我这里是以2个字段作为分组

 Map<String, Map<String, List<ProcessLog>>> processLogs = list.stream().collect(
                Collectors.groupingBy(
                        ProcessLog::getServerName, groupingBy_WithNullKeys(ProcessLog::getUser)
                )
        );

你可能感兴趣的:(java代码小技巧)