簡體   English   中英

如何在 Java 中簡化此方法?

[英]How can I simplify this method in Java?

我怎樣才能簡化這個表達式 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;
}

我的觀點是,對於每個鍵,我想根據getSortedValues(entry.getValue ())對其值進行排序。 但是在這里,我不是在一行中做,而是在功能上制作另一個新的 object 和循環。

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

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

如何在保持操作不變的同時簡化此方法。

只需添加accountCredit.sort(...); 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));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM