如何在Java中简化这个方法?

huangapple go评论86阅读模式
英文:

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

    return groupedByOwnerId.entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getKey, entry -> getSortedValues(entry.getValue())));
}

我的意思是对于每个键我想根据 `getSortedValues​​(entry.getValue())` 对其值进行排序但是在这里我不是一行代码就完成了而是创建了另一个新对象并进行了循环

请注意,代码的改变并没有改变操作的逻辑,只是将循环部分转换为了流式操作,以更简洁的方式实现相同的功能。

英文:

How can I simplify this expression in Java

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

    for (Map.Entry&lt;String, List&lt;Account&gt;&gt; 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&lt;String, List&lt;Account&gt;&gt; result = new HashMap&lt;&gt;();

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

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

答案1

得分: 1

stream 之前添加 accountCredit.sort(...);

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));
}
英文:

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

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

huangapple
  • 本文由 发表于 2020年10月25日 01:36:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/64516260.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定