List grouping summary and calculation

Group calculation

scenes to be used:

In a list, group according to a certain field and perform calculations on data in different groups.

@Data
public class order implements Serializable {

    private static final long serialVersionUID = 7353320757077145027L;


    /**
     * Command id
     */
    private String id;

    /**
     * Net value
     */
    private BigDecimal net;

    //slightly

}

/**
     * 1. Group the incoming data set and the specified grouping field
     * 2. Calculate the specified field after the grouping is completed
     * 3. Return a new data set
     *
     * @param dataList The data set that needs to be grouped
     * @param groupFunc grouping field
     * @return List<order>
     */
    private List<order> groupParamList(List<order> dataList, Function<order, ?> groupFunc) {         return dataList.stream().collect(Collectors.groupingBy(                 groupFunc         )).values().stream().flatMap(list -> Stream.of(list.stream().reduce((data1, data2) -> {             data1.setPrizeCount(data1.getNet().add(data2 .getNet());             return data1;         }).orElse(new order()))).collect(Collectors.toList());     }






    @Test
    public void groupParamList() {
        order order = new order();
        order.setId(1);
        order.setNet(new BigDecimal("1"));

        order order2 = new order();
        order2.setId(1);
        order2.setNet(new BigDecimal("2"));

        

        List<order> dataList = new ArrayList<>();
        dataList.add(order);
        dataList.add(order2);

        log.info("Before grouping---");
        dataList.forEach(data -> {             log.info(data.toString() + "\n");         });

        List<order> dataListNew = groupParamList(dataList, order::getId());

        log.info("After grouping---");
        dataListNew.forEach(data -> {             log.info(data.toString() + "\n");         });     }


Guess you like

Origin blog.csdn.net/qq_44691484/article/details/128388839