【发布时间】:2019-09-06 19:09:16
【问题描述】:
我正在尝试使用 lambda 表达式迭代 Map 的 List 并且在迭代时我必须使用字段设置器方法在一个 POJO 中设置值。当Map 的List 中有null 值时,问题就出现了(特别是应该处理映射字段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());
})
【问题讨论】:
-
StringUtils.isEmpty没有根据其文档返回空指针异常。 -
检查 lambda 中的“结果”是否为空。使用调试器。您可以让您的代码更一步一步地分析发生的每一个小步骤、每个变量等。您还可以使用 Optionals 来避免 NullPointerExceptions。
-
这还有问题吗?它可以帮助澄清您的代码,什么是
response或与r1相同。null是哪个值,你得到的NullPointerException的堆栈跟踪是什么?
标签: java string lambda nullpointerexception null