Java 从列表列表映射到pojo总计

Java 从列表列表映射到pojo总计,java,Java,我需要处理我的数组列表并计算从每个帐户余额中提取的总数。 根据作业,我不能有另一个数据结构 ArrayList<Customer> = { { Forename= Blue, Surname= Red, CustomerId= 2119954221, Age= 98, Accounts= [Account Name = Current Account, Account ID = 1, Accounts Balance = 0.0, Account total = 0.0, Acco

我需要处理我的数组列表并计算从每个帐户余额中提取的总数。 根据作业,我不能有另一个数据结构

ArrayList<Customer> = {
{  Forename= Blue, Surname= Red, CustomerId= 2119954221, Age= 98, Accounts= [Account Name = Current Account, Account ID = 1, Accounts Balance = 0.0, Account total = 0.0, Account Name = Current Account, Account ID = 2, Accounts Balance = 0.0, Account total = 0.0] }
{  Forename= Orange, Surname= Yellow, CustomerId= 1448877171, Age= 32, Accounts= [Account Name = Current Account, Account ID = 3, Account Balance = 10000.0, Account total = 10000.0, Account Name = Current Account, Account ID = 4, Account Balance = -100.0, Account total = -100.0, Account Name = Savings Account, Account ID = 26634, Account Balance = 10.0, Account total = 10.0] }
...................
}
这不起作用,因为上一个总计已添加到下一个客户

一个可能的解决方案是向客户和帐户添加accountKey,这样我可以在两个列表中都有一个常量,以检查它们是否匹配并计算总数。 也许这会阻止向下一个客户添加余额

我不认为这是一个尝试,tho


感谢您的阅读。

据我所知,您正试图获取客户所有账户的余额

public static void calculateAccountTotal(){
    for (Customer c : CUSTOMERS) {
        double total = 0;
        for (Account a : c.getAccounts()) {
            total += a.getAccountBalance();
        }
        c.setTotal(total);
    }
}

在account中存储帐户余额会使您的帐户对象持有错误的数据。更好的选择是客户层面的平衡。

谢谢,我现在明白我错在哪里了。客户是一个,客户是多个。不过,如果我想在每个帐户中都有一个变量,如“TotalForallaccounts”,那怎么可能实现呢?@Scilla我们可以说一切都是可能的,但这样做会给你带来很多麻烦。您需要有一个同步机制,以确保客户的所有帐户具有相同的值。在同步机制变得更加复杂的多线程环境中,这变得更加棘手。因此,代码的性能将显著降低。最好找到简单的方法来避免代码中的副作用。一个好的起点是使用纯函数。除此之外,还有许多其他未提及的考虑。你的解释是有道理的。谢谢你抽出时间。我想我建议的解决方案“为了同步目的,在客户和帐户中设置一个常量”就是您所说的“同步机制”。
public static void calculateAccountTotal(){
double total = 0;
        for (Customer c : CUSTOMERS) {
            for (Account a : c.getAccounts()) {
                total += a.getAccountBalance();
                a.setTotal(total);
            }
      }
}
public static void calculateAccountTotal(){
    for (Customer c : CUSTOMERS) {
        double total = 0;
        for (Account a : c.getAccounts()) {
            total += a.getAccountBalance();
        }
        c.setTotal(total);
    }
}