我有以下对象列表
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,值应该是帐户列表
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)
如何做到这一点?
3条答案
按热度按时间1tuwyuhd1#
你可以用
Collectors.groupingBy
.演示
tcbh2hod2#
bkkx9g8r3#
我宁愿使用
Collectors.toMap
方法具有三个参数,以确保清晰: