我的世界充钱网站怎么做,西安网,如何在ftp做网站,网站建设免费模板下载归约#xff0c;也称缩减#xff0c;顾名思义#xff0c;是把一个流缩减成一个值#xff0c;能实现对集合求和、求乘积和求最值操作。 「案例一#xff1a;求Integer集合的元素之和、乘积和最大值。」
public class StreamTest {public static void main(String[] args) …归约也称缩减顾名思义是把一个流缩减成一个值能实现对集合求和、求乘积和求最值操作。 「案例一求Integer集合的元素之和、乘积和最大值。」
public class StreamTest {public static void main(String[] args) {ListInteger list Arrays.asList(1, 3, 2, 8, 11, 4);// 求和方式1OptionalInteger sum list.stream().reduce((x, y) - x y);// 求和方式2OptionalInteger sum2 list.stream().reduce(Integer::sum);// 求和方式3Integer sum3 list.stream().reduce(0, Integer::sum);// 求乘积OptionalInteger product list.stream().reduce((x, y) - x * y);// 求最大值方式1OptionalInteger max list.stream().reduce((x, y) - x y ? x : y);// 求最大值写法2Integer max2 list.stream().reduce(1, Integer::max);System.out.println(list求和 sum.get() , sum2.get() , sum3);System.out.println(list求积 product.get());System.out.println(list求和 max.get() , max2);}
}
「案例二求所有员工的工资之和和最高工资。」
public class StreamTest {public static void main(String[] args) {ListPerson personList new ArrayListPerson();personList.add(new Person(Tom, 8900, 23, male, New York));personList.add(new Person(Jack, 7000, 25, male, Washington));personList.add(new Person(Lily, 7800, 21, female, Washington));personList.add(new Person(Anni, 8200, 24, female, New York));personList.add(new Person(Owen, 9500, 25, male, New York));personList.add(new Person(Alisa, 7900, 26, female, New York));// 求工资之和方式1OptionalInteger sumSalary personList.stream().map(Person::getSalary).reduce(Integer::sum);// 求工资之和方式2Integer sumSalary2 personList.stream().reduce(0, (sum, p) - sum p.getSalary(),(sum1, sum2) - sum1 sum2);// 求工资之和方式3Integer sumSalary3 personList.stream().reduce(0, (sum, p) - sum p.getSalary(), Integer::sum);// 求最高工资方式1Integer maxSalary personList.stream().reduce(0, (max, p) - max p.getSalary() ? max : p.getSalary(),Integer::max);// 求最高工资方式2Integer maxSalary2 personList.stream().reduce(0, (max, p) - max p.getSalary() ? max : p.getSalary(),(max1, max2) - max1 max2 ? max1 : max2);System.out.println(工资之和 sumSalary.get() , sumSalary2 , sumSalary3);System.out.println(最高工资 maxSalary , maxSalary2);}
}