我在将老式转换为Optional.ifPresent. 这是之前版本的代码。State state = State.OK;final Optional<Person> checkExistingPerson = checkIt();if(checkExistingPerson.isPresent()) { Person person = checkExistingPerson.get(); if("blah".equals(person.getName())) { state = State.DUPLICATE; } else { state = State.RESTORED; } return Member(person.getId(), state);}return Member(null, state);这是Optional.ifPresent用法State state = State.OK;final Optional<Person> checkExistingPerson = checkIt();checkExistingPerson.ifPresent(person -> { if("blah".equals(person.getName())) { state = State.DUPLICATE; } else { state = State.NEW; } return Member(person.getId(), state);});return Member(null, state);而且,这是 IntelliJ 强迫我更改它的屏幕截图。Optional关于我的问题,最好的方法是什么?谢谢!
3 回答
呼啦一阵风
TA贡献1802条经验 获得超6个赞
您不能从 lambda 表达式中更改局部变量的值。此外,ifPresent不能返回值,因为它的返回类型是void.
相反,您应该使用Optional.map,Optional如果它存在,它会转换被包装的对象:
return checkExistingPerson
.map(person -> new Member(
person.getId(),
"blah".equals(person.getName()) ? State.DUPLICATE : State.RESTORED))
.orElse(new Member(null, State.OK));
添加回答
举报
0/150
提交
取消