|
| 1 | +package lambdasinaction.chap5; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +import static java.util.stream.Collectors.groupingBy; |
| 6 | + |
| 7 | +public class GroupingTransactions { |
| 8 | + |
| 9 | + public static List<Transaction> transactions = Arrays.asList( new Transaction(Currency.EUR, 1500.0), |
| 10 | + new Transaction(Currency.USD, 2300.0), |
| 11 | + new Transaction(Currency.GBP, 9900.0), |
| 12 | + new Transaction(Currency.EUR, 1100.0), |
| 13 | + new Transaction(Currency.JPY, 7800.0), |
| 14 | + new Transaction(Currency.CHF, 6700.0), |
| 15 | + new Transaction(Currency.EUR, 5600.0), |
| 16 | + new Transaction(Currency.USD, 4500.0), |
| 17 | + new Transaction(Currency.CHF, 3400.0), |
| 18 | + new Transaction(Currency.GBP, 3200.0), |
| 19 | + new Transaction(Currency.USD, 4600.0), |
| 20 | + new Transaction(Currency.JPY, 5700.0), |
| 21 | + new Transaction(Currency.EUR, 6800.0) ); |
| 22 | + public static void main(String ... args) { |
| 23 | + groupImperatively(); |
| 24 | + groupFunctionally(); |
| 25 | + |
| 26 | + } |
| 27 | + |
| 28 | + private static void groupImperatively() { |
| 29 | + Map<Currency, List<Transaction>> transactionsByCurrencies = new HashMap<>(); |
| 30 | + for (Transaction transaction : transactions) { |
| 31 | + Currency currency = transaction.getCurrency(); |
| 32 | + List<Transaction> transactionsForCurrency = transactionsByCurrencies.get(currency); |
| 33 | + if (transactionsForCurrency == null) { |
| 34 | + transactionsForCurrency = new ArrayList<>(); |
| 35 | + transactionsByCurrencies.put(currency, transactionsForCurrency); |
| 36 | + } |
| 37 | + transactionsForCurrency.add(transaction); |
| 38 | + } |
| 39 | + |
| 40 | + System.out.println(transactionsByCurrencies); |
| 41 | + } |
| 42 | + |
| 43 | + private static void groupFunctionally() { |
| 44 | + Map<Currency, List<Transaction>> transactionsByCurrencies = transactions.stream().collect(groupingBy(Transaction::getCurrency)); |
| 45 | + System.out.println(transactionsByCurrencies); |
| 46 | + } |
| 47 | + |
| 48 | + public static class Transaction { |
| 49 | + private final Currency currency; |
| 50 | + private final double value; |
| 51 | + |
| 52 | + public Transaction(Currency currency, double value) { |
| 53 | + this.currency = currency; |
| 54 | + this.value = value; |
| 55 | + } |
| 56 | + |
| 57 | + public Currency getCurrency() { |
| 58 | + return currency; |
| 59 | + } |
| 60 | + |
| 61 | + public double getValue() { |
| 62 | + return value; |
| 63 | + } |
| 64 | + |
| 65 | + @Override |
| 66 | + public String toString() { |
| 67 | + return currency + " " + value; |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + public enum Currency { |
| 72 | + EUR, USD, JPY, GBP, CHF |
| 73 | + } |
| 74 | +} |
0 commit comments