Java8Stream详解~归约(reduce)归约,也称缩减,顾名思义,是把⼀个流缩减成⼀个值,能实现对集合求和、求乘积和求最值操作。
「案例⼀:求Integer集合的元素之和、乘积和最⼤值。」
1public class StreamTest {
2 public static void main(String[] args) {
3  List<Integer> list = Arrays.asList(1, 3, 2, 8, 11, 4);
4  // 求和⽅式1
5  Optional<Integer> sum = list.stream().reduce((x, y) -> x + y);
6  // 求和⽅式2
7  Optional<Integer> sum2 = list.stream().reduce(Integer::sum);
8  // 求和⽅式3
9  Integer sum3 = list.stream().reduce(0, Integer::sum);
10
11  // 求乘积
12  Optional<Integer> product = list.stream().reduce((x, y) -> x * y);
13
14  // 求最⼤值⽅式1
15  Optional<Integer> max = list.stream().reduce((x, y) -> x > y ? x : y);
16  // 求最⼤值写法2
17  Integer max2 = list.stream().reduce(1, Integer::max);
18
19  System.out.println("list求和:" + () + "," + () + "," + sum3);
20  System.out.println("list求积:" + ());
21  System.out.println("list求和:" + () + "," + max2);
22 }
23}
「案例⼆:求所有员⼯的⼯资之和和最⾼⼯资。」
1public class StreamTest {
2 public static void main(String[] args) {
3  List<Person> personList = new ArrayList<Person>();
4  personList.add(new Person("Tom", 8900, 23, "male", "New York"));
5  personList.add(new Person("Jack", 7000, 25, "male", "Washington"));
6  personList.add(new Person("Lily", 7800, 21, "female", "Washington"));
7  personList.add(new Person("Anni", 8200, 24, "female", "New York"));
8  personList.add(new Person("Owen", 9500, 25, "male", "New York"));
9  personList.add(new Person("Alisa", 7900, 26, "female", "New York"));
10
11  // 求⼯资之和⽅式1:
12  Optional<Integer> sumSalary = personList.stream().map(Person::getSalary).reduce(Integer::sum);
13  // 求⼯资之和⽅式2:
java stream14  Integer sumSalary2 = personList.stream().reduce(0, (sum, p) -> sum += p.getSalary(),
15    (sum1, sum2) -> sum1 + sum2);
16  // 求⼯资之和⽅式3:
17  Integer sumSalary3 = personList.stream().reduce(0, (sum, p) -> sum += p.getSalary(), Integer::sum);
18
19  // 求最⾼⼯资⽅式1:
20  Integer maxSalary = personList.stream().reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary(),
21    Integer::max);
22  // 求最⾼⼯资⽅式2:
23  Integer maxSalary2 = personList.stream().reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary(),
24    (max1, max2) -> max1 > max2 ? max1 : max2);
25
26  System.out.println("⼯资之和:" + () + "," + sumSalary2 + "," + sumSalary3);
27  System.out.println("最⾼⼯资:" + maxSalary + "," + maxSalary2);
28 }
29}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。