简体   繁体   中英

How can I simplify this method in Java?

How can I simplify this expression in Java

public Map<String, List<Account>> findAllAccountsCredits(final List<String> listOfIds) {
    List<Account> accountCredit = executeQueryForAccountCredits(listOfIds);
    Map<String, List<Account>> groupedByOwnerId = accountCredit.stream().collect(Collectors.groupingBy(Account::getOwnerId));
    Map<String, List<Account>> result = new HashMap<>();

    for (Map.Entry<String, List<Account>> entry : groupedByOwnerId.entrySet()) {
        result.put(entry.getKey(), getSortedValues(entry.getValue()));
    }

    return result;
}

My point is, then for each key, I want to sort its values according to getSortedValues(entry.getValue ()) . But here, instead of doing it in one line, I'm functionally making another new object and loop.

Map<String, List<Account>> result = new HashMap<>();

for (Map.Entry<String, List<Account>> entry : groupedByOwnerId.entrySet()) {
    result.put(entry.getKey(), getSortedValues(entry.getValue()));
}

How can I simplify this method while keeping the operation as it is now.

Just add accountCredit.sort(...); before stream :

public Map<String, List<Account>> findAllAccountsCredits(final List<String> listOfIds) {
    List<Account> accountCredit = executeQueryForAccountCredits(listOfIds);
    accountCredit.sort(...);
    return accountCredit.stream().collect(Collectors.groupingBy(Account::getOwnerId));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM