背景

线上某任务出现报警,报错日志如下:

java.lang.NullPointerException: null
at java.util.HashMap.merge(HashMap.java:1225)
at java.util.stream.Collectors.lambda$toMap$58(Collectors.java:1320)
at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1380)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
at com.xxx.web.controller.TaskController.getOmsAccidCloudCCUserIdMap(TaskController.java:648)
at com.xxx.web.controller.TaskController.executePushNewRegisterLead(TaskController.java:400)
at com.xxx.web.controller.TaskController.pushNewRegister(TaskController.java:145)

对应出错的代码:

omsAccidCloudCCUserIdMap = administratorList.stream()
.collect(Collectors.toMap(Administrator::getAccid,administrator
-> cloudccAccidUserIdMap.get(administrator.getCloudccAccid())));

已知administratorList不含有null元素,administratorListcloudccAccidUserIdMap都不为nullAdministrator::getAccid也不会返回null值。

问题定位

综上所述,NPE只可能发生在

administrator -> cloudccAccidUserIdMap.get(administrator.getCloudccAccid())

但是HashMap是允许一个null key和多个null value的啊,查看openjdk的HashMap源码,看到javadoc也是如此说明的:

Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

那究竟是哪里出了问题呢,回过头仔细看报错信息,发现是java.util.HashMap.merge(HashMap.java:1225)抛出的异常,查看merge源码:

    @Override
public V merge(K key, V value,
BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
if (value == null)
throw new NullPointerException();
if (remappingFunction == null)
throw new NullPointerException();
...
return value;
}

向上追溯,看到java.util.Map接口中对merge的定义:

/**
* If the specified key is not already associated with a value or is
* associated with null, associates it with the given non-null value.
* Otherwise, replaces the associated value with the results of the given
* remapping function, or removes if the result is {@code null}. This
* method may be of use when combining multiple mapped values for a key.
* For example, to either create or append a {@code String msg} to a
* value mapping:
*
* <pre> {@code
* map.merge(key, msg, String::concat)
* }</pre>
*
* <p>If the function returns {@code null} the mapping is removed. If the
* function itself throws an (unchecked) exception, the exception is
* rethrown, and the current mapping is left unchanged.
*
* @implSpec
* The default implementation is equivalent to performing the following
* steps for this {@code map}, then returning the current value or
* {@code null} if absent:
*
* <pre> {@code
* V oldValue = map.get(key);
* V newValue = (oldValue == null) ? value :
* remappingFunction.apply(oldValue, value);
* if (newValue == null)
* map.remove(key);
* else
* map.put(key, newValue);
* }</pre>
*
* <p>The default implementation makes no guarantees about synchronization
* or atomicity properties of this method. Any implementation providing
* atomicity guarantees must override this method and document its
* concurrency properties. In particular, all implementations of
* subinterface {@link java.util.concurrent.ConcurrentMap} must document
* whether the function is applied once atomically only if the value is not
* present.
*
* @param key key with which the resulting value is to be associated
* @param value the non-null value to be merged with the existing value
* associated with the key or, if no existing value or a null value
* is associated with the key, to be associated with the key
* @param remappingFunction the function to recompute a value if present
* @return the new value associated with the specified key, or null if no
* value is associated with the key
* @throws UnsupportedOperationException if the {@code put} operation
* is not supported by this map
* (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>)
* @throws ClassCastException if the class of the specified key or value
* prevents it from being stored in this map
* (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if the specified key is null and this map
* does not support null keys or the value or remappingFunction is
* null
* @since 1.8
*/
default V merge(K key, V value,
BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
Objects.requireNonNull(remappingFunction);
Objects.requireNonNull(value);
V oldValue = get(key);
V newValue = (oldValue == null) ? value :
remappingFunction.apply(oldValue, value);
if(newValue == null) {
remove(key);
} else {
put(key, newValue);
}
return newValue;
}

可以看到,Collectors.toMap在底层使用的是Map::merge方法,而merge方法不允许null value,无论该Map实例是否支持null value(但是允许null key如果Map实例支持的话)。

@throws NullPointerException if the specified key is null and this map does not support null keys or the value or remappingFunction is null

问题解决

找到原因了,那么如何解决呢?这个问题在stackoverflow上也有一篇帖子说明了如何fix这个问题https://stackoverflow.com/questions/24630963/java-8-nullpointerexception-in-collectors-tomap

不使用Collectors.toMap,改为使用forEach遍历列表手动转换。

Collectors.toMap不允许Null Value导致NPE的更多相关文章

  1. 使用Collectors.toMap遇到NullPointerException

    这个坑也是踩过好几次了,记录一笔. 当试图使用Collectors.toMap将一个stream收集为Map的时候,若构造map的valueMapper返回null时,则会报NullPointerEx ...

  2. Java8 Collectors.toMap的坑

    按照常规思维,往一个map里put一个已经存在的key,会把原有的key对应的value值覆盖,然而通过一次线上问题,发现Java8中的Collectors.toMap反其道而行之,它默认给抛异常,抛 ...

  3. java 8 lamda Stream的Collectors.toMap 参数

    使用toMap()函数之后,返回的就是一个Map了,自然会需要key和value.toMap()的第一个参数就是用来生成key值的,第二个参数就是用来生成value值的.第三个参数用在key值冲突的情 ...

  4. java8 list转Map报错Collectors.toMap :: results in "Non-static method cannot be refernced from static context"

    1.问题:java8 list转Map 报错Collectors.toMap :: results in "Non-static method cannot be refernced fro ...

  5. MySQL为Null会导致5个问题,个个致命!

    在正式开始之前,我们先来看下 MySQL 服务器的配置和版本号信息,如下图所示: "兵马未动粮草先行",看完了相关的配置之后,我们先来创建一张测试表和一些测试数据. -- 如果存在 ...

  6. 如何优雅的使用 参数 is null而不导致全表扫描(破坏索引)

    相信大家在很多实际业务中(特别是后台系统)会使用到各种筛选条件来筛选结果集 首先添加测试数据 ), Age INT) go CREATE INDEX idx_age ON TempList (Age) ...

  7. ExceptionInChainedOperatorException:flink写hbase对于null数据导致数据导致出现异常

    使用的flink版本:1.9.1 异常描述 需求: 从kafka读取一条数据流 经过filter初次筛选符合要求的数据 然后通过map进行一次条件判断再解析.这个这个过程中可能返回null或目标输出o ...

  8. 服务器字体导致NPE

    服务器字体问题 服务器在windows下运行正常. 搬到Linux之后,注册页有个404??? HTTP Status 500 – Internal Server Error Type 异常报告 消息 ...

  9. if(response.isSuccess){}else{}的方式,如果我们由于忽略没有设置success字段的值,就可能导致

    在日常开发中,我们会经常要在类中定义布尔类型的变量,比如在给外部系统提供一个RPC接口的时候,我们一般会定义一个字段表示本次请求是否成功的. 关于这个”本次请求是否成功”的字段的定义,其实是有很多种讲 ...

随机推荐

  1. 《C Primer Plus(第6版)中文版》勘误

    搬运自己2016年11月28日发布于SegmentFault的文章.链接:https://segmentfault.com/a/1190000007626460 本勘误由本人整理并发布,仅针对下方列出 ...

  2. 异步编程之Async,Await和ConfigureAwait的关系

    在.NET Framework 4.5中,async / await关键字已添加到该版本中,简化多线程操作,以使异步编程更易于使用.为了最大化利用资源而不挂起UI,你应该尽可能地尝试使用异步编程.虽然 ...

  3. Scala数据结构

    Scala数据结构 主要的集合特质 Scala同时支持可变集合和不可变集合,优先采用不可变集合.集合主要分为三大类:序列(List),集(set),映射(map).所有的集合都扩展自Iterable特 ...

  4. 2019牛客多校第二场D-Kth Minimum Clique

    Kth Minimum Clique 题目传送门 解题思路 我们可以从没有点开始,把点一个一个放进去,先把放入一个点的情况都存进按照权值排序的优先队列,每次在新出队的集合里增加一个新的点,为了避免重复 ...

  5. 简单分析线程获取ReentrantReadWriteLock 读锁的规则

    1. 问题 最近有同事问了我一个问题,在Java编程中,当有一条线程要获取ReentrantReadWriteLock的读锁,此时已经有其他线程获得了读锁,AQS队列里也有线程在等待写锁.由于读锁是共 ...

  6. 一位 iOS 大牛的 BAT面试心得与经验总结,送给正在迷茫 的你!

    前言: 目前形势,参加到 iOS 队伍的人是越来越多,可以说是已经达到了供过于求的地步了. 今年,找过工作人可能会更深刻地体会到今年的就业形势不容乐观,之前实习的时候就想着写一篇面经,后来忙就给忘了, ...

  7. MVC设计模式与Java Web经典三层架构

    MVC设计模式 MVC的概念 首先我们需要知道MVC模式并不是javaweb项目中独有的,MVC是一种软件工程中的一种软件架构模式,把软件系统分为三个基本部分:模型(Model).视图(View)和控 ...

  8. python面向对象-封装-property-接口-抽象-鸭子类型-03

    封装 什么是封装: # 将复杂的丑陋的隐私的细节隐藏到内部,对外提供简单的使用接口 或 # 对外隐藏内部实现细节,并提供访问的接口 为什么需要封装 1.为了保证关键数据的安全性 2.对外部隐藏内部的实 ...

  9. python正则-re的使用

    今天在刷题的时候用到了正则,用的过程中就感觉有点不太熟练了,很久没有用正则都有点忘了.所以现在呢,我们就一起来review一下python中正则模块re的用法吧. 今天是review,所以一些基础的概 ...

  10. sklearn 第二篇:数据预处理

    sklearn.preprocessing包提供了几个常用的转换函数,用于把原始特征向量转换为更适合估计器的表示. 转化器(Transformer)用于对数据的处理,例如标准化.降维以及特征选择等,提 ...