Java8 Stream详解~归约(reduce)
生活随笔
收集整理的這篇文章主要介紹了
Java8 Stream详解~归约(reduce)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
歸約,也稱縮減,顧名思義,是把一個流縮減成一個值,能實現(xiàn)對集合求和、求乘積和求最值操作。
「案例一:求Integer集合的元素之和、乘積和最大值。」
public class StreamTest {public static void main(String[] args) {List<Integer> list = Arrays.asList(1, 3, 2, 8, 11, 4);// 求和方式1Optional<Integer> sum = list.stream().reduce((x, y) -> x + y);// 求和方式2Optional<Integer> sum2 = list.stream().reduce(Integer::sum);// 求和方式3Integer sum3 = list.stream().reduce(0, Integer::sum);// 求乘積Optional<Integer> product = list.stream().reduce((x, y) -> x * y);// 求最大值方式1Optional<Integer> 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) {List<Person> personList = new ArrayList<Person>();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"));// 求工資之和方式1:Optional<Integer> sumSalary = personList.stream().map(Person::getSalary).reduce(Integer::sum);// 求工資之和方式2:Integer sumSalary2 = personList.stream().reduce(0, (sum, p) -> sum += p.getSalary(),(sum1, sum2) -> sum1 + sum2);// 求工資之和方式3:Integer sumSalary3 = personList.stream().reduce(0, (sum, p) -> sum += p.getSalary(), Integer::sum);// 求最高工資方式1:Integer maxSalary = personList.stream().reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary(),Integer::max);// 求最高工資方式2:Integer 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);} }總結
以上是生活随笔為你收集整理的Java8 Stream详解~归约(reduce)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 浅析段错误和栈溢出
- 下一篇: OFD文件结构--Pages~Page_