简体   繁体   中英

How do i perform arithmetic operation on elements of list in Java?

An entity named Transaction have two type of transactions ' credit ' and ' debit '. Objects of entity are date , id (used sequence generator), amount and a foreign key .

What I have done is that I crated two Typedqueries to select transaction by transaction types(credit or debit) and store the Typedqueries result in two List.

I want to return the difference of total amount from credit transactions to total amount from debit type transactions( summation of all credit transaction - summation of all debit transactions ). It will give me balance.

My code:

public Result getBalanceByTransaction(Http.Request request,String userName)
    {
        Account a; Wallet w;
        a = jpaApi.withTransaction(entityManager -> {
            return entityManager.createNamedQuery("detailsByName",Account.class).setParameter("name",userName).getSingleResult();
        }); long account_id = a.getId();
        w = jpaApi.withTransaction(entityManager -> {
           return entityManager.createNamedQuery("walletById",Wallet.class).setParameter("id",account_id).getSingleResult();
        });

        String queryForCredit ="select transaction.amount from Transaction transaction where transaction.txnType ='CREDIT' and transaction.wallet.id =:id";
        String queryForDebit = "select transaction.amount from Transaction transaction where transaction.txnType ='DEBIT' and transaction.wallet.id =:id";
        TypedQuery <Transaction> allCredit = jpaApi.withTransaction(entityManager -> {
           return entityManager.createQuery(queryForCredit,Transaction.class);
        });
        List <Transaction> allCreditTxn = allCredit.getResultList();
        TypedQuery <Transaction> allDebit = jpaApi.withTransaction(entityManager -> {
           return entityManager.createQuery(queryForDebit,Transaction.class);
        });
        List <Transaction> allDebitTxn = allDebit.getResultList();


    }

How do i perform arithmetic operation on 'amount' object of multiple entities stored in List.

Since you are looking for total amounts you should perform the summation within the JPL query, to avoid querying the whole Transaction entity. You can do this with SUM() operator, as suggested in this answer :

SELECT SUM(t.amount) 
FROM Transaction t
WHERE t.txnType ='CREDIT'
AND t.wallet.id =:id

If you are attempting to calculate the account balance you might want to change your database model to store this value somewhere eg Wallter.balance field. Calculating this every single time balance is displayed feels wasteful.

As others have mentioned you can compute the sum within your query already but if you want to sum it up in a List , you can do that in a functional way by using map and reduce() and method references .

List<Transaction> credit = Arrays.asList(new Transaction(100d), new Transaction(100d), new Transaction(100d), new Transaction(100d));
List<Transaction> debit = Arrays.asList(new Transaction(100d), new Transaction(250d));

// sum up all amount for credit and debit
var totalCredit = credit.stream().map(Transaction::getAmount).reduce(0d, Double::sum);
var totalDebit = debit.stream().map(Transaction::getAmount).reduce(0d, Double::sum);

// print result
System.out.println(totalCredit - totalDebit);

Expected output:

50.0

Transaction.java

public class Transaction {
    private double amount;

    public Transaction(double amount) {
        this.amount = amount;
    }

    public double getAmount() {
        return amount;
    }

    public void setAmount(double amount) {
        this.amount = amount;
    }
}

If your Transaction uses another datatype than double , note that sum does also exist for those other datatype eg Integer:sum .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM