fork download
  1. import com.google.common.collect.*;
  2. import java.util.*;
  3. import java.time.*;
  4.  
  5. class Transaction {
  6. double amount;
  7. String transactionType;
  8. LocalDate date;
  9.  
  10. Transaction(double amount, String transactionType, String date) {
  11. this.amount = amount;
  12. this.transactionType = transactionType;
  13. this.date = LocalDate.parse(date);
  14. }
  15.  
  16. public double getAmount() {
  17. return amount;
  18. }
  19.  
  20. public String getTransactionType() {
  21. return transactionType;
  22. }
  23.  
  24. public LocalDate getDate() {
  25. return date;
  26. }
  27. }
  28.  
  29. public class Main {
  30. public static void processTransactions(List<Transaction> transactions) {
  31. // Filter by "Credit" and group by date
  32. ImmutableListMultimap<LocalDate, Transaction> transactionsByDate = Multimaps.index(
  33. FluentIterable.from(transactions)
  34. .filter(t -> "Credit".equals(t.getTransactionType())),
  35. Transaction::getDate);
  36.  
  37. // Calculate and print average amount for each date
  38. for (LocalDate date : transactionsByDate.keySet()) {
  39. Collection<Transaction> dateTransactions = transactionsByDate.get(date);
  40. double average = dateTransactions.stream()
  41. .mapToDouble(Transaction::getAmount)
  42. .average()
  43. .orElse(0.0);
  44. System.out.println(date + " - " + String.format("%.2f$", average));
  45. }
  46. }
  47.  
  48. public static void main(String[] args) {
  49. List<Transaction> transactions = Arrays.asList(
  50. new Transaction(500, "Credit", "2023-05-27"),
  51. new Transaction(1500, "Debit", "2023-04-06"),
  52. new Transaction(1800, "Credit", "2023-08-06"),
  53. new Transaction(250, "Credit", "2023-05-27"),
  54. new Transaction(500, "Debit", "2023-05-27")
  55. );
  56.  
  57. processTransactions(transactions);
  58. }
  59. }
  60.  
Success #stdin #stdout 0.25s 60648KB
stdin
Standard input is empty
stdout
2023-05-27 - 375.00$
2023-08-06 - 1800.00$