【问题标题】:Handling Null Values in Lambda Expression处理 Lambda 表达式中的空值
【发布时间】:2019-09-06 19:09:16
【问题描述】:

我正在尝试使用 lambda 表达式迭代 MapList 并且在迭代时我必须使用字段设置器方法在一个 POJO 中设置值。当MapList 中有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


【解决方案1】:

问题已解决,我使用 Optional 如下所示。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-16
    • 1970-01-01
    • 1970-01-01
    • 2013-09-15
    相关资源
    最近更新 更多