java 数据类型:集合接口Collection之 Stream 的reduce方法

Stream 的reduce递归计算

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

/**
 * @ClassName StreamReduceExample
 * @projectName: object1
 * @author: Zhangmingda
 * @description: 递归处理元素,例如计算人对象,年龄属性的和
 * date: 2021/4/12.
 */
public class StreamReduceExample {
    private static class Person{
        private String name;
        private Integer age;

        public Person(String name, Integer age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public Integer getAge() {
            return age;
        }

        @Override
        public String toString() {
            return "Person{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
    public static void main(String[] args) {
        List<Person> persons = Arrays.asList(
                new Person("张三", 13),
                new Person("李四", 22),
                new Person("王五", 27)
                );
        System.out.println(persons);//[Person{name='张三', age=13}, Person{name='李四', age=22}, Person{name='王五', age=27}]
        Integer ageSum  = persons.stream().map(person -> person.getAge()).reduce((age1,age2) -> age1 + age2).get();
        System.out.println(ageSum); //62
        //persons.stream().reduce((p1,p2) -> p1.getAge() + p2.getAge()).get(); 
        // 注意,reduce要求传入值和返回值类型相同,传入Person对象返回也需要返回对象,如上注释的写法返回int编译报错
    }
}

 

posted on 2021-04-12 23:10  zhangmingda  阅读(376)  评论(0编辑  收藏  举报

导航