web123456

Summarize BigDecimal using Stream aggregation function

The results of database searches often include collections such as List, and the storage method in the collection is a JAVA object, and BigDecimal fields exist in the object. It feels very troublesome to accumulate with for or iterator traversal. The stream aggregation function solves this problem well. Make a note mark

POJO

package test;

import ;

/**
  * User Entity Class
  *
  * @author suddev
 * @create2018-02-26 11:03 am
  **/
public class User {
    private long id;
    private BigDecimal money;

    public User(long id, BigDecimal money) {
        this.id = id;
        this.money = money;
    }
    // getter&setter
}

In the entity class, we can see that the entity has a money attribute of BigDecimal, taking the example of calculating the total amount of money for all query users:

package test;

import ;
import ;
import ;

/**
  * Test class
  *
  * @author suddev
 * @create2018-02-26 11:03 am
  **/
public class Test {
    public static void main(String[] args) {
        // Prepare data
        List<User> userList = new ArrayList<User>();
        for (int i = 0; i < 100; i++) {
            User user = new User(i,new BigDecimal(i+"."+i));
            (user);
        }
        // for version
        BigDecimal result1 = ;
        for (User user : userList) {
            result1 = (());
        }
        ("result1 = "+result1);
        // java 8 stream version
        BigDecimal result2 = ()
                // Take out the mongey of the user object and map it to Bigdecimal
                .map(User::getMoney)
                // Use reduce aggregation function to implement the accumulator
                .reduce(,BigDecimal::add);
        ("result2 = "+result2);
    }
}

Map is an intermediate operation for stream objects. Through a given method, it can correspond to each element in the stream object to another object. Here, the user object's money is taken out and the map is Bigdecimal

reduce is a final operation, which can cut elements through a certain method. The result of this operation will be returned in an Optional variable. It can be used to implement many aggregation methods such as count, max, min, etc.
Here is the second method of reducing overloading
T reduce(T identity, BinaryOperator accumulator);
The first parameter is the initial value we give, and the second parameter is the accumulator. You can use the implementation interface to complete the desired operation. Here we use Bigdecimal's add method
Finally, reduce will return the calculated result

Reference documentation:
Java 8 series: The universal reduce in Stream
Adding up BigDecimals using Streams