1.3 流

Collection主要为了存储和访问数据,而Stream则主要用于描述对数据的计算。

筛选金额较高的交易,按货币分组。

外部迭代

public static Map<Currency, List<Transaction>> filterAndGroup(List<Transaction> transactions) {
    Map<Currency, List<Transaction>> transactionsByCurrencies = new HashMap<>();
    for (Transaction transaction : transactions) {
        if (transaction.getPrice() > 1000) {
            Currency currency = transaction.getCurrency();
            List<Transaction> transactionsForCurrency = transactionsByCurrencies.get(currency);
            if (transactionsForCurrency == null) {
                transactionsForCurrency = new ArrayList<>();
                transactionsByCurrencies.put(currency, transactionsForCurrency);
            }
            transactionsForCurrency.add(transaction);
        }
    }
    return transactionsByCurrencies;
}

内部迭代-顺序处理

public static Map<Currency, List<Transaction>> streamFilterAndGroup(List<Transaction> transactions) {
    return transactions.stream()
            .filter(t -> t.getPrice() > 1000)
            .collect(Collectors.groupingBy(Transaction::getCurrency));
}

内部迭代-并行处理

public static Map<Currency, List<Transaction>> parallelStreamFilterAndGroup(List<Transaction> transactions) {
    return transactions.parallelStream()
            .filter(t -> t.getPrice() > 1000)
            .collect(Collectors.groupingBy(Transaction::getCurrency));
}
posted @ 2023-06-10 16:49  夜是故乡明  阅读(3)  评论(0编辑  收藏  举报