Stream系列Reduce方法使用
Posted javaweibiancheng
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Stream系列Reduce方法使用相关的知识,希望对你有一定的参考价值。
裁减计算
视频讲解: https://www.bilibili.com/video/av77715582/
EmployeeTest.java
package com.example.demo; import lombok.extern.log4j.Log4j2; import org.junit.Test; import javax.swing.plaf.basic.BasicTreeUI; import java.util.*; import java.util.stream.Collector; import java.util.stream.Collectors; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @Log4j2 public class EmployeeTest extends BaseTestCase { @Test public void reduce(){ double dSum = list.stream().map(Employee::getSalary).reduce(Double::sum).get(); assertTrue(dSum == 8000); double dSum2 = list.stream().map(Employee::getSalary).reduce((a,b) ->a + b).get(); assertTrue(dSum == dSum2); double dSum3 = list.stream().map(Employee::getSalary).reduce((a,b) ->{ System.out.println("a:"+a+" b"+b); return a + b; }).get(); assertTrue(dSum == dSum3); double dSum4 = list.stream().map(Employee::getSalary).reduce(AddUtils::add).get(); assertTrue(dSum == dSum4); double dSum5 = list.stream().map(Employee::getSalary).reduce(0.00,Double::sum); assertTrue(dSum == dSum5); } static class AddUtils { public static Double add(Double a, Double b) { return a + b; } } }
BaseTestCase.java
package com.example.demo; import java.util.Arrays; import java.util.List; public class BaseTestCase { protected static final List<Employee> list = Arrays.asList( new Employee(1, "Alex", 1000), new Employee(2, "Michael", 2000), new Employee(3, "Jack", 1500), new Employee(4, "Owen", 1500), new Employee(5, "Denny", 2000)); }
关注公众号,坚持每天3分钟学习
以上是关于Stream系列Reduce方法使用的主要内容,如果未能解决你的问题,请参考以下文章
Stream api reduce方法在尝试对大数求和时返回负值[重复]
如何使用 stream().reduce() 基于谓词从一个列表中创建 2 个列表 [重复]