java map<String,List<Object>>set时注意空值问题

今天上线发现报了一个奇怪的错:

  private String getUserType(Map<String, List<Type>> userTypeMap, String userId) {
    List<Type> typeList = userTypeMap.get(userId);
    if (CollectionUtils.isEmpty(typeList)) {
      return "";
    }
    //下行报空指针
    List<Type> filterList = typeList.stream()
                                .filter(r -> !StringUtils.isBlank(r.getName()))
                                .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(filterList)) {
      return "游客";
    }
    return "用户";
  }

其中 List<UserType> filterList = userTypeList.stream().filter(r -> "Y".equals(r.getValue1())).collect(Collectors.toList()); 这行一直报空指针问题,百思不得其解。

能走到这一步时,userTypeList肯定不为空,而r.getName() 为空也不会报错.

最后通过debug发现,typeList的size为1,但是里面的object为null,往上找发现创建userTypeMap时,set进去了空值

private Map<String, List<Type>> getUserTypeMap(Set<String> allUserIdSet) {

    if (CollectionUtils.isEmpty(allUserIdSet)) {
      return Collections.EMPTY_MAP;
    }

    //type表里存了typeName等其他信息
    List<Type> typeList = typeMapper.listAll();
    Map<String, Type> typeMap = typeList.stream().collect(Collectors.toMap(Type::getId, Function.identity()));

    //userType里仅存了typeId信息
    List<UserType> userTypeRelList = userTypeMapper.findByUserIdSet(allUserIdSet);
    
    Map<String, List<Type>> userIdTypeMap = new HashMap<>();
    for (UserType userType : userTypeRelList) {
      Type type = typeMap.get(userType.getUserId());
      //未判断type是否为空值
      if (userIdTypeMap.containsKey(userType.getUserId()) && !CollectionUtils.isEmpty(userIdTypeMap.get(userType.getUserId()))) {
        List<Type> list = userIdTypeMap.get(userType.getUserId());
        list.add(role);
        userIdTypeMap.put(userType.getUserId(), list);
      } else {
        userIdTypeMap.put(userType.getUserId(), Stream.of(type).collect(Collectors.toList()));
      }
    }
    return userIdTypeMap;
  }

如代码所示,未判断从typeMap里取出来的type是不是空值,所以导致userIdTypeMap里set进去了一行key = userId, value = Stream.of(null).collect(Collectors.toList())的值,最终导致空指针。

吸取教训,以后从Map中get值后,需强制校验value是否为空,再执行下面逻辑。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值