@Data
public class MonthlyBudgetReportResponse {
@ApiModelProperty(value = "数据类型(0-经营分类数据;1-总合计)")
private String resultType;
@ApiModelProperty(value = "品类名")
private String catalogName;
@ApiModelProperty(value = "收入预算本年")
private String incomeBudgetBn;
@ApiModelProperty(value = "收入预算本期")
private String incomeBudgetBq;
@ApiModelProperty(value = "收入本期完成数")
private String incomeBudgetBqComplete;
@ApiModelProperty(value = "毛利预算本年")
private String profitBudgetBn;
@ApiModelProperty(value = "毛利预算本期")
private String profitBudgetBq;
@ApiModelProperty(value = "毛利本期完成数")
private String profitBudgetBqComplete;
}
这个是从数据库查询返回的实体类,现在我要实现对这个List的集合的收入以及毛利的汇总求和。数据库的实现想过,但是要多一条sql,而且原本sql已经很复杂了,不想再为一个单独求和再复制一遍。用java代码如何实现?有lamda表达式的最好。
//假设这和个是已经从数据库查出来的单条数据。有多条
List<MonthlyBudgetReportResponse> resultList
@Data
public class MonthlyBudgetReportResponse {
@ApiModelProperty(value = "数据类型(0-经营分类数据;1-总合计)")
private String resultType;
@ApiModelProperty(value = "品类名")
private String catalogName;
@ApiModelProperty(value = "收入预算本年")
private String incomeBudgetBn;
@ApiModelProperty(value = "收入预算本期")
private String incomeBudgetBq;
@ApiModelProperty(value = "收入本期完成数")
private String incomeBudgetBqComplete;
@ApiModelProperty(value = "毛利预算本年")
private String profitBudgetBn;
@ApiModelProperty(value = "毛利预算本期")
private String profitBudgetBq;
@ApiModelProperty(value = "毛利本期完成数")
private String profitBudgetBqComplete;
public MonthlyBudgetReportResponse(String incomeBudgetBn, String profitBudgetBq) {
this.incomeBudgetBq = incomeBudgetBn;
this.profitBudgetBq = profitBudgetBq;
}
public static void main(String[] args) {
List<MonthlyBudgetReportResponse> reportResponseList = new ArrayList<>();
reportResponseList.add(new MonthlyBudgetReportResponse("11.1","15.1"));
reportResponseList.add(new MonthlyBudgetReportResponse("12.3","13.2"));
BigDecimal reduce = reportResponseList.stream().map( i -> new BigDecimal(i.getIncomeBudgetBq())).reduce(BigDecimal.ZERO, BigDecimal::add);
System.out.println(reduce);
}
resultList.stream().mapToInt(a -> Integer.parseInt(a.getIncomeBudgetBn())).sum() 这样试一下
resultList.stream().collect(Collectors.summingInt(e -> Integer.parseInt(e.getIncomeBudgetBn())));
Integer result = resultList.stream().collect(Collectors.summingInt(MonthlyBudgetReportResponse::getIncomeBudgetBn));
有这样想过,但是不支持字符串类型
有没有解决办法
把字符串强转成int啊,想想怎么转
给出两种解答方法:
方式一:题主的方法解答:
Integer collect1 = list.stream().filter(h -> StringUtils.isNotBlank(h.getIncomeBudgetBn())).collect(Collectors.summingInt(h -> Integer.parseInt(h.getIncomeBudgetBn().trim())));
方式二:最优的写法:
Integer result = list.stream().filter(h -> StringUtils.isNotBlank(h.getIncomeBudgetBn())).mapToInt(h -> Integer.parseInt(h.getIncomeBudgetBn().trim())).sum();
望采纳,谢谢🙏