基于Java的Stream流实现对某些列的求和(适用于财务计算)
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.*;
import java.math.BigDecimal;
import java.util.*;
public class PageSumUtils {
public static JSONObject getSummary(@NonNull Object data, @NonNull String[] total_column, @Nullable String[] no_total_column, String decimal, String total_index_column, String total_name) {
JSONObject totalJson = new JSONObject();
List<JSONObject> maps = JSONObject.parseArray(JSON.toJSONString(data), JSONObject.class);
if (StringUtils.isEmpty(decimal)) {
decimal = "%.2f";
}
if (total_index_column != null && total_name != null) {
totalJson.put(total_index_column, total_name);
}
for (String key : total_column) {
Optional<BigDecimal> reduce = maps.stream()
.filter(temp -> !Objects.equals(temp.get(key), ""))
.map(temp -> new BigDecimal(temp.get(key).toString()))
.reduce(BigDecimal::add);
if (reduce.isPresent()) {
totalJson.put(key, String.format(decimal, reduce.get()));
} else {
totalJson.put(key, 0);
}
}
if (no_total_column != null) {
for (String key : no_total_column) {
totalJson.put(key, "");
}
}
return totalJson;
}
}