Nichole
Nichole

Reputation: 219

How to regroup a list of custom objects into a map in Java?

I have following list of objects

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)));

I want to transfer above to Map and key should be the customerID and values should be list of 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)

How to achieve this?

Upvotes: 1

Views: 400

Answers (3)

user16314724
user16314724

Reputation:

I would prefer to use the Collectors.toMap method with three parameters for clarity:

Map<Integer, List<Account>> map = accounts.stream()
        .collect(Collectors.toMap(
                // key - customerID
                e -> e.getCustomer().getCustomerID(),
                // value - List<Account>
                e -> List.of(e),
                // merge two lists
                (l1, l2) -> Stream.of(l1, l2)
                        .flatMap(List::stream)
                        .collect(Collectors.toList())));

Upvotes: 0

Unmitigated
Unmitigated

Reputation: 89254

You can use Collectors.groupingBy.

Map<Integer, List<Account>> map =
    accounts.stream().collect(Collectors.groupingBy(Account::getCustomerID));

Demo

Upvotes: 4

Frighi
Frighi

Reputation: 466

List<Account> accounts = new ArrayList<>();
accounts.add(new Account(1, "abc", 17998210, 190));
accounts.add(new Account(2, "hsj", 6786179, 190));
accounts.add(new Account(4, "ioip", 246179, 191));
accounts.add(new Account(4, "ewrew", 90179, 191));

Map<Integer, List<Account>> accountsMap = new HashMap<>();

for (Account account : accounts) {
    accountsMap.computeIfAbsent(account.customerID, k -> new ArrayList<>()).add(account);
}

Upvotes: 1

Related Questions