如何在
Map<String,List<Account>>
内找到最大销量
class Account {
String hashId;
String address;
BigDecimal sold;
}
我看到了这个讨论,但我无法针对我的情况修改它,我必须搜索所有列表才能获得最大的销售价值。
如果您只想要最大
sold
而没有其他,您可以执行以下操作:
这里我假设你的
Map
被命名为“map”,并且 sold
有一个名为 getSold
的 getter。
这将返回一个具有最大值的可选值。
map.values()
.stream()
.flatMap(listOfAccounts -> listOfAccounts.stream().map(Account::getSold))
.max(BigDecimal::compareTo);
你可以这样做。这假设你有一个吸气剂。它返回包含最高销量的帐户。
给定
Map<String, List<Account>> accounts = null;
所有价值中最好的
Account best =
accounts.values().stream().flatMap(Collection::stream)
.max(Comparator.comparing(Account::getSold))
.get();
每个键的最佳功能
Map<String, Account> bestOfEach = accounts.entrySet().stream()
.collect(Collectors.toMap(Entry::getKey,
e -> e.getValue().stream()
.max(Comparator
.comparing(Account::getSold))
.get()));