处理 lambda 表达式中的空值



我正在尝试使用 lambda 表达式迭代MapList,在迭代时,我必须使用字段设置器方法在一个 POJO 中设置值。当MapListnull值时(特别是应该处理的地图字段null(,就会出现问题。我尝试了很多事情来处理NullPointerException.

Employee employee = new Employee();
employee.setEmployeeName(result.getOrDefault("employeeName", "").toString());
employee.setEmployeeName(!StringUtils.isEmpty(result.get("employeeName").toString()) ? result.get("employeeName").toString() : " "); 
// when i am using this solution it is not giving null pointer exception 
// but if the value is null then it is returning "null" value it means 
// null as a string which shouldn't be the expected output. 
employee.setEmployeeName(String.valueOf(result.get("employeeName").equals("null") ? "" : result.get("employeeName")));
List<Map<String,Object>> r1 = new ArrayList<Map<String,Object>>();
response.forEach(result -> { 
employee.setEmployeeName(result.getOrDefault("employeeName", "").toString());
})

已解决的问题我使用了 可选 如下所示。

Optional.ofNullable(result.get("employeeName")).orElse(" ").toString()

最新更新