今天上线发现报了一个奇怪的错:
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是否为空,再执行下面逻辑。