英文:
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<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.
答案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<String, List<Account>> findAllAccountsCredits(final List<String> listOfIds) {
List<Account> accountCredit = executeQueryForAccountCredits(listOfIds);
accountCredit.sort(...);
return accountCredit.stream().collect(Collectors.groupingBy(Account::getOwnerId));
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论