我有以下对象列表
class Account {
int id;
String type;
int balance;
Customer customer;
// getters setters
}
class Customer {
int customerID;
}
List<Account> accounts = new ArrayList<>();
accounts.add(new Account(1, "abc", 17998210, new Customer(190)));
accounts.add(new Account(2, "hsj", 6786179, new Customer(190)));
accounts.add(new Account(4, "ioip", 246179, new Customer(191)));
accounts.add(new Account(4, "ewrew", 90179, new Customer(191)));
我想将上面的转移到 Map 并且键应该是 customerID 并且值应该是 Account 列表
Map<Integer, List<Account>>
Key Value
190 -> Account(1, "abc", 17998210, 190)
Account(2, "hsj", 6786179, 190)
191 -> Account(4, "ioip", 246179, 191)
Account(4, "ewrew", 90179, 191)
如何实现这一目标?
您可以使用Collectors.groupingBy
.
Map<Integer, List<Account>> map =
accounts.stream().collect(Collectors.groupingBy(Account::getCustomerID));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句