в Stream получить List
имеются некоторые Paymentы от одного аккаунта другому, нужно получить: сколько раз каждый аккаунт получал Payment. По коду: группирую list по получателям, дальше из мапы получаю ключ, формирую list из AccountInfo, key.hashCode() - заглушка, по факту вместо этой заглушки нужно получить value.size() - тут и застрял
public AccountInfo(Account account, Integer count) {
this.account = account;
this.count = count;
}
List<AccountInfo> accountInfoList = list.stream()
.collect(Collectors.groupingBy(Payment::getTo))
.entrySet().stream()
.map(Map.Entry::getKey)
.map(key -> new AccountInfo(key, key.hashCode()))
.collect(Collectors.toList());
Ответы (1 шт):
Автор решения: Nowhere Man
→ Ссылка
По идее проще было бы сразу рассчитать частоту платежей для счёта-получателя, используя Collectors.groupingBy и Collectors.summingInt, а затем преобразовать элементы мапы:
List<Payment> list = getPayments(); // входной лист платежей
Map<Account, Integer> map = list.stream()
.collect(Collectors.groupingBy(
Payment::getTo,
Collectors.summingInt(p -> 1)
));
List<AccountInfo> result = map.entrySet()
.stream()
.map(e -> new AccountInfo(e.getKey(), e.getValue()))
.collect(Collectors.toList());
В принципе, и показанное решение можно слегка изменить для желаемого результата:
List<AccountInfo> result = list
.stream()
.collect(Collectors.groupingBy(Payment::getTo)) // Map<Account, List<Payment>>
.entrySet()
.stream()
.map(e -> new AccountInfo(e.getKey(), e.getValue().size()))
.collect(Collectors.toList());