1. 程式人生 > >java8 利用reduce實現將列表中的多個元素的屬性求和並返回

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); } }