java元帅

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
  49 随笔 :: 0 文章 :: 0 评论 :: 19852 阅读

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

 

posted on   java元帅  阅读(1490)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· 我与微信审核的“相爱相杀”看个人小程序副业
· DeepSeek “源神”启动!「GitHub 热点速览」
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
点击右上角即可分享
微信分享提示