1. 使用groupBy时,如果分组的 key 为 null,会抛出异常,可以写如下工具类规避这个问题:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * Java8 stream操作 GroupBy 设置键允许为null
 */
public class StreamGroupByUtil {
    public static <T, A> Collector<T, ?, Map<A, List<T>>> groupByWithNullKeys(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<Integer, List<ClassA>> map = classAList.stream()
                .collect(StreamGroupByUtil.groupByWithNullKeys(ClassA::getParentId));

 

posted on 2021-05-24 15:33  miaoying  阅读(5390)  评论(1编辑  收藏  举报