JAVA 8 Stream 自查自用
//dm
@Data private static class Cat { private String name ; private BigDecimal price; private int age; }
/** * 属性求和 */ @Test public void testSum(){ Cat cat = new Cat(); cat.setAge(1); cat.setName("tudou"); cat.setPrice(new BigDecimal(1)); Cat cat2 = new Cat(); cat2.setAge(1); cat2.setName("tudou2"); cat2.setPrice(new BigDecimal(1)); final List<Cat> cats = Arrays.asList(cat, cat2); final Integer reduce = cats.stream().reduce(0, (temp, y) -> temp + y.getAge(), Integer::sum); Assert.isTrue(reduce==2); }
/** * 属性相乘求和 */ @Test public void testSumMultiple() { Cat cat = new Cat(); cat.setAge(1); cat.setName("tudou"); cat.setPrice(new BigDecimal(1)); Cat cat2 = new Cat(); cat2.setAge(1); cat2.setName("tudou2"); cat2.setPrice(new BigDecimal(1)); final List<Cat> cats = Arrays.asList(cat, cat2); final BigDecimal reduce = cats.stream().reduce(BigDecimal .ZERO, (temp, y) -> temp.add(new BigDecimal(y.getAge()).multiply(y.getPrice())), BigDecimal::add); Assert.isTrue(reduce.equals(new BigDecimal(3))); }
参考文章 https://www.baeldung.com/java-stream-reduce