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
?
To add to this answer, if printing is not desirable, then list(sum. items()) will do the trick. ( sum. items() is not a list.)
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.
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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With