Java 8 - 如何将多个字段合并为一个dto? [英] Java 8 - how sum many fields into a dto?

查看:1098
本文介绍了Java 8 - 如何将多个字段合并为一个dto?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个类似的项目:

Let's say I have a class Item like this:

class Item {  
    private long id;  
    private BigDecimal value1;  
    private BigDecimal value2;  
    private BigDecimal value3;  
}  

然后我有一个包含许多itens的列表,我想知道总和每个值:

Then I have a list with many itens, I want to know the sum of each of the values:

所以,我知道我可以做类似的事情

So, I know I could do something like

BigDecimal v1 = list.stream().map(Item::value1).reduce(BigDecimal.ZERO, BigDecimal::add);

但是,这样我需要为每个值做同样的事情,我想知道如果有某种方法可以将每个属性总结为只有一个Dto:

However, this way I would need to do the same for each value, I'd like to know if there's some way of summing each attribute into only one Dto like:

class TotalItem {  
    private BigDecimal value1;  
    private BigDecimal value2;  
    private BigDecimal value3;  
}  

TotalItem t = list.stream().map(???).reduce(BigDecimal.ZERO, BigDecimal::add);

这可能吗?

谢谢提前。

推荐答案

我没有测试它,但我认为你可以在项目上实现添加功能喜欢:

I didn't test it but I think that you can implement add function on Item like:

public Item add(Item other) {
   Item newItem = new Item(this.value1 + other.value1,
              this.value2 + other.value2,
              this.value3 + other.value3);

   return newItem;
}

然后执行:

Item t = list.stream().reduce(BigDecimal.ZERO, Item::add);

这篇关于Java 8 - 如何将多个字段合并为一个dto?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆