Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of int from list of object [duplicate]

Tags:

java

java-8

I have a class as following

class Account{
    String Name;
    int amount;
}

If I have a list as List<Account> then how can I get the total amount from this list without using any loop like for or foreach?

like image 776
LynAs Avatar asked Sep 18 '15 11:09

LynAs


People also ask

How do you sum duplicates in a list in Python?

To add to this answer, if printing is not desirable, then list(sum. items()) will do the trick. ( sum. items() is not a list.)

How to find duplicate values in ArrayList?

One of the most common ways to find duplicates is by using the brute force method, which compares each element of the array to every other element. This solution has the time complexity of O(n^2) and only exists for academic purposes.


2 Answers

You can create a Stream of your accounts using stream(), map that stream to the amount of each account using mapToInt and sum the resulting IntStream using IntStream.sum().

List<Account> accounts = new ArrayList<>();
int totalAmount = accounts.stream().mapToInt(Account::getAmount).sum();

This code assumes that there is a getter getAmount for amount.

like image 105
Tunaki Avatar answered Oct 25 '22 17:10

Tunaki


If you don't mind using a third party library, there is sumOfInt available in Eclipse Collections. It returns a long instead of an int, so the possibility of an overflow is much less likely.

You can either use a static utility method on the Iterate class which works with any java.lang.Iterable type as follows:

List<Account> accounts = new ArrayList<>();
long sum = Iterate.sumOfInt(accounts, Account::getAmount);

Or you if your list is a MutableList, you can use the method directly available on the list.

MutableList<Account> accounts = Lists.mutable.empty();
long sum = accounts.sumOfInt(Account::getAmount);

Note: I am a committer for Eclipse Collections

like image 26
Donald Raab Avatar answered Oct 25 '22 18:10

Donald Raab