-2

I have a list of objects which contains the medium of transaction and transaction amount. I want to find the total amount for particular transaction.

For example- I have the following objects in list -

Credit card 10
Debit card 20
Credit card 30
Credit card 20
Debit card  20
Digital Wallet 30
Debit card 40

I want output like this -

Credit Card 60
Debit card 80
Digital Wallet 30

I want it to do using Java 8 stream. Can anyone please help!

Thiyagu
  • 17,362
  • 5
  • 42
  • 79
vikash singh
  • 1,479
  • 1
  • 19
  • 29
  • 1
    Did you try anything? – Thiyagu Aug 10 '18 at 05:40
  • I started with [How to sum a list of integers with java streams?](https://stackoverflow.com/questions/30125296/how-to-sum-a-list-of-integers-with-java-streams) and got a basic example running, but required three lines (one for each group), I then used [Java 8 – Stream Collectors groupingBy examples](https://www.mkyong.com/java8/java-8-collectors-groupingby-and-mapping-example/), which, if you read through all the examples will provide you with an "exact example" of what you are looking for - all in 10 minutes - and no, I'm not posting it - that's an adventure I won't rob you of ;) – MadProgrammer Aug 10 '18 at 05:53
  • I already tried - transaction.stream.collect(Collectors.groupingBy()...). But, inside grouping by I was not able to map the transaction type of the transaction object using t -> t.getTransactionMedium() – vikash singh Aug 10 '18 at 06:12

1 Answers1

1

You can do it like so,

Map<String, Double> txAmountByMedium = transactions.stream()
    .collect(Collectors.groupingBy(Transaction::getMedium, 
        Collectors.summingDouble(Transaction::getAmount)));

First group the transactions by their medium using groupingBy collector. Then use a downstream collector to sum the transaction amount for each group.

Ravindra Ranwala
  • 20,744
  • 6
  • 45
  • 63