java8 利用reduce实现将列表中的多个元素的属性求和并返回

利用java8流的特性,我们可以实现list中多个元素的 属性求和 并返回。
案例:
有一个借款待还信息列表,其中每一个借款合同包括:本金、手续费;
现在欲将 所有的本金求和、所有的手续费求和。
我们可以使用java8中的函数式编程,获取list的流,再利用reduce遍历递减方式将同属性(本金、手续费)求和赋予给一个新的list中同类型的对象实例,即得到我们需要的结果:

A a = list.stream()
                .reduce(
                        (x , y) -> new A( (x.getPrincipal() + y.getPrincipal()), (x.getFee() + y.getFee()) ) )
                .orElse( new A(0, 0) );

示例代码如下:

package org.byron4j.eight;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

public class ReduceTwoObjectAddProp {


    class A{
        int principal = 0;
        int fee = 0;
        public A(int principal, int fee) {
            super();
            this.principal = principal;
            this.fee = fee;
        }
        public A() {
            super();
            // TODO Auto-generated constructor stub
        }
        public int getPrincipal() {
            return principal;
        }
        public void setPrincipal(int principal) {
            this.principal = principal;
        }
        public int getFee() {
            return fee;
        }
        public void setFee(int fee) {
            this.fee = fee;
        }
        @Override
        public String toString() {
            return "A [principal=" + principal + ", fee=" + fee + "]";
        }

    }


    @Test
    public void test() {


        List<A> list = new ArrayList<A>();
        list.add(new A(1, 2));
        list.add(new A(100, 200));

        A a = list.stream()
                .reduce(
                        (x , y) -> new A( (x.getPrincipal() + y.getPrincipal()), (x.getFee() + y.getFee()) ) )
                .orElse( new A(0, 0) );
        System.out.println(a);
    }

}

猜你喜欢

转载自blog.csdn.net/zixiao217/article/details/80673897