Bog*_*ogl 2 java lambda dictionary java-8
我试图在使用Lambda表达式进行计算后得到数字,但得到错误.
我正在使用的lambda表达式:
int num = Optional.ofNullable(list.stream().filter(x->x.getType().getTypeId()==Type.getTypeId()).limit(1).map(x->x.getNum())).get();
Run Code Online (Sandbox Code Playgroud)
过滤后,我想获得第一个检索到的值.但我得到的错误是
cannot convert from Stream<Integer> to int
Run Code Online (Sandbox Code Playgroud)
所以,目前我使用的方式是
Optional<> li = list.stream().filter(x->x.getType().getTypeId()==Type.getTypeId()).findFirst();
if (li.isPresent()) {
num = li.map(x-> x.getNum()).get();
}
Run Code Online (Sandbox Code Playgroud)
但是,我正在寻找上述是否可以在一行而不是额外的if声明
早些时候,我试图get()用findFirst(),但它给人nullpointerException.如何安全地检索该值.
list.stream().filter(x->x.getType().getTypeId()==Type.getTypeId()).limit(1).map(x->x.getNum())返回一个Stream.你缺乏findFirst终端操作:
int num =
list.stream()
.filter(x->x.getType().getTypeId()==Type.getTypeId())
.map(x->x.getNum())
.findFirst()
.orElse(0); // default value in case the Stream is empty after the filtering
Run Code Online (Sandbox Code Playgroud)