首页 > 编程语言 >java8 stream按某个字段分组,允许分组字段是null

java8 stream按某个字段分组,允许分组字段是null

时间:2022-10-29 23:00:39浏览次数:49  
标签:java stream List util 分组 import null

Map<String, List<Dto>> deviceMap = deviceList.stream().collect(Collectors.groupingBy(Dto::getFlowId));

场景:如果getFlowId是null.就会包以下错误

element cannot be mapped to a null 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;
                }
        );
    }
}

使用:

Map<Integer, List<Dto>> map = classAList.stream()
                .collect(StreamGroupByUtil.groupByWithNullKeys(Dto::getFlowId));

 

标签:java,stream,List,util,分组,import,null
From: https://www.cnblogs.com/zhaoyijunjava/p/16840131.html

相关文章