[英]lambda retrieve integer from map
I am trying to get the number after doing calculations using Lambda expression, but getting the error. 我正在尝试使用Lambda表达式进行计算后获得数字,但出现错误。
The lambda expression I am using: 我正在使用的lambda表达式:
int num = Optional.ofNullable(list.stream().filter(x->x.getType().getTypeId()==Type.getTypeId()).limit(1).map(x->x.getNum())).get();
After filtering, I want to get the first retrieved value. 过滤后,我想获取第一个检索到的值。 But I am getting the error as 但我得到的错误
cannot convert from Stream<Integer> to int
So, currently the way I am using is 所以,目前我使用的方式是
Optional<> li = list.stream().filter(x->x.getType().getTypeId()==Type.getTypeId()).findFirst();
if (li.isPresent()) {
num = li.map(x-> x.getNum()).get();
}
But, I was looking if the above could be done in a single line rather than extra if
statement 但是,我正在寻找是否可以单行完成上述操作,而不是额外的if
语句
Earlier, I tried the get()
with findFirst()
, but it was giving nullpointerException
. 之前,我尝试使用findFirst()
进行get()
findFirst()
,但是它给出了nullpointerException
。 How can I safely retrieve the value. 如何安全地获取值。
list.stream().filter(x->x.getType().getTypeId()==Type.getTypeId()).limit(1).map(x->x.getNum())
returns a Stream
. list.stream().filter(x->x.getType().getTypeId()==Type.getTypeId()).limit(1).map(x->x.getNum())
返回一个Stream
。 You are lacking the findFirst
terminal operation: 您缺少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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.