简体   繁体   English

处理 Lambda 表达式中的空值

[英]Handling Null Values in Lambda Expression

I am trying to iterate List of Map using lambda expression and while iterating I have to set the values in one POJO using field setter method.我正在尝试使用 lambda 表达式迭代Map List ,并且在迭代时我必须使用字段设置器方法在一个 POJO 中设置值。 The problem comes when there are null values in List of Map (in particular map field null should be handled).Map Listnull值时就会出现问题(特别是应该处理 map 字段null )。 I tried so many things to handle NullPointerException .我尝试了很多方法来处理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,如下所示。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM