java中stream、collect和forEach组合的代码流

java中stream、collect和forEach组合的代码流,java,dictionary,generics,java-stream,core,Java,Dictionary,Generics,Java Stream,Core,我在我的公司项目中遇到过这样的代码 void pAccount(List<Account> accounts) { accounts.stream() .filter(o->getKey(o) != null) .collect(Collectors.groupingBy(this::getKey)) .forEach(this::pAccounts); } private Key getKey(Account acco

我在我的公司项目中遇到过这样的代码

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
}
void pAccount(列出账户){
accounts.stream()
.filter(o->getKey(o)!=null)
.collect(收集器.groupingBy(this::getKey))
.forEach(此::pAccounts);
}
私钥getKey(帐户){
返回keyRepository.getKeyById(account.getId());
}
私有无效数据包计数(密钥、列表帐户){
//一些代码
}
在调试过程中,我们得出结论,
pAccount(List accounts)
调用
pAccounts(Key-Key,List accounts)

我曾试图在网上找到类似的例子,但没有找到与这种行为相匹配的


我想知道这是流中允许我们这样做的某种功能,还是其他功能。

您所指的方法是在
forEach(this::pAccounts)
中调用的。 这是因为
collect(Collectors.groupingBy(this::getKey))
返回一个
映射


Map
上的
forEach
根据,采用
BiConsumerdoes
this:
调用该方法,尤其是我的方法scenario@abhi314
forEach
调用作为lambda传递的方法,
是一个方法引用-
(k,v)->this.pAccounts(k,v)的语法糖
。尽管我可能错了,但我不建议为
getKey
创建
n
查询,而是首先收集所有ID,然后在一个查询中获取所有密钥,并创建一个新的流来处理结果。@Naman为什么删除[java-8]标记?@Andronicus版本标记一直有争议(不会有太多的争论)。因此,除非由询问者放置或与代码相关(特定API)在这个问题上,我认为不应该需要特定于版本的标记。例如,如果OP可能在这里寻找Java-14解决方案,该怎么办?因此,我建议仅在询问者将其作为绑定或代码中的API与任何其他版本无关时才添加版本标记。不过,这仍然取决于您的选择。@Naman获得了,感谢clarification,祝你有美好的一天!