【Bug】Collectors.toMap 重复问题与空值报错问题

Collectors.toMap 重复问题与空值报错问题

public static void main(String[] args) {
	SysAdmin sysAdmin = new SysAdmin();
	sysAdmin.setAdminCode("123");
	sysAdmin.setAdminName("111");
	
	SysAdmin sysAdmin2 = new SysAdmin();
	sysAdmin2.setAdminCode("123");
	sysAdmin2.setAdminName("456");
	
	List<SysAdmin> list = new ArrayList<>();
	list.add(sysAdmin);
	list.add(sysAdmin2);
	
	Map<String, String> map = list.stream().collect(Collectors.toMap(key -> key.getAdminCode(), val -> Optional.ofNullable(val.getAdminName()).orElse(StringUtils.EMPTY), (k1, k2) -> k2));
	System.out.println(JSONObject.toJSONString(map));
	
	Map<String, String> map2 = list.stream().collect(HashMap::new, (m, v) -> m.put(v.getAdminCode(), v.getAdminName()), HashMap::putAll);
	System.out.println(JSONObject.toJSONString(map2));
}

空值报错,使⽤ Map.merge ⽅法合并时,merge 不允许 value 为 null 导致的。

The main reason that nulls aren’t allowed in ConcurrentMaps (ConcurrentHashMaps, ConcurrentSkipListMaps) is that ambiguities that may be just barely tolerable in non-concurrent maps can’t be accommodated. The main one is that if map.get(key) returns null, you can’t detect whether the key explicitly maps to null vs the key isn’t mapped. In a non-concurrent map, you can check this via map.contains(key), but in a concurrent one, the map might have changed between calls.

key 的⼆义性

Map.merge 为了兼容 ConcurrentHashMap 还有 ConcurrentSkipListMap 等多线程环境下使⽤的数据结构和使⽤ CAS 的实现不允许 value 为 null。key 不能为 null 是因为⽆法分辨是 key 没找到的原因所以为 null,还是 key 值本⾝就为 null。

From the author of ConcurrentHashMap himself (Doug Lea)
The main reason that nulls aren’t allowed in ConcurrentMaps (ConcurrentHashMaps, ConcurrentSkipListMaps) is that ambiguities that may be just barely tolerable in non-concurrent maps can’t be accommodated. The main one is that if map.get(key) returns null, you can’t detect whether the key explicitly maps to null vs the key isn’t mapped. In a non-concurrent map, you can check this via map.contains(key), but in a concurrent one, the map might have changed between calls.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值