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
posted @ 2022-06-15 17:14  xudong5273  阅读(1941)  评论(0编辑  收藏  举报