java中stream的map和mapToInt方法使用
stream()中的maptoint(ToIntFunction mapper)返回一个IntStream其中包含给定函数应用于此流得元素的结果
maptoint有sum()求和方法
public static void main(String[] args) {
List<User> list = new ArrayList<>();
for (int i = 0; i < 5; i++) {
User a = new User();
a.setAge(5);
if (i == 4) {
a.setAge(null);
}
list.add(a);
}
// 空指针
// int sum = list.stream().mapToInt(User::getAge).sum();
// 正确写法
int sum = list.stream().mapToInt(o -> Objects.isNull(o.getAge()) ? 0 : o.getAge()).sum();
System.out.println(sum);
}
输出
20