小编mge*_*cht的帖子

Java条件运算符中的可选项导致NullPointerException

我有一个包含两个参数的Dto的List <>:type和value.现在我想找到类型为"C"的列表中的一个元素并读出该值.

执行以下java代码时,我得到一个我不明白的NullPointerException:

class TestDto
{
    private String type;
    private Double value;

    TestDto(final String type, final Double value)
    {
        this.type = type;
        this.value = value;
    }

    public String getType() { return type; }
    public Double getValue() { return value; }
}
Run Code Online (Sandbox Code Playgroud)

...

List<TestDto> testList = new ArrayList<>();
testList.add(new TestDto("A", 11.111d));
testList.add(new TestDto("B", 22.222d));
testList.add(new TestDto("C", null));

Predicate<TestDto> typePredicate = c-> c.getType().equals("C");
Optional optional = testList.stream().filter(typePredicate).findFirst();

if(optional.isPresent()){
    System.out.println("if-output = " + ((TestDto) optional.get()).getValue());
}

Double value = optional.isPresent() ? ((TestDto) optional.get()).getValue() …
Run Code Online (Sandbox Code Playgroud)

java nullpointerexception conditional-operator optional

4
推荐指数
1
解决办法
738
查看次数