我在公司项目中遇到过代码,如下所示
void pAccount(List<Account> accounts) {
accounts.stream()
.filter(o->getKey(o) != null)
.collect(Collectors.groupingBy(this::getKey))
.forEach(this::pAccounts);
}
private Key getKey(Account account) {
return keyRepository.getKeyById(account.getId());
}
private void pAccounts(Key key , List<Account> accounts) {
//Some Code
}
在调试时我们得出的结论是pAccount(List<Account> accounts)
来电 pAccounts(Key key , List<Account> accounts
.
我尝试在网上查找类似的示例,但没有找到与此行为匹配的内容。
我想知道这是否是流中允许我们执行此操作的某种功能,或者是其他功能。
最佳答案
您引用的方法在 forEach(this::pAccounts)
中调用。
这是因为collect(Collectors.groupingBy(this::getKey))
返回 Map
.
forEach
上Map
,根据javadoc ,需要 BiConsumer<? super K,? super V>
,其中第一个参数是 K
类型的键第二个 - V
类型的值。
所以这个forEach
不是 Stream
上的方法,但是在Map
上.
关于java - java中stream、collect、forEach组合的代码流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60737626/