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

abh*_*314 3 java generics dictionary core java-stream

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

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
}
Run Code Online (Sandbox Code Playgroud)

在调试时,我们得出的结论是pAccount(List<Account> accounts)调用pAccounts(Key key , List<Account> accounts.

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

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

And*_*cus 5

您所指的方法在forEach(this::pAccounts). 这是因为collect(Collectors.groupingBy(this::getKey))返回一个Map.

forEachMap,根据Javadoc中,需要一个BiConsumer<? super K,? super V>,其中,第一参数的类型的键K和第二-类型的值V

所以这forEach不是 on 的方法Stream,而是 on Map

  • @abhi314 `forEach` 调用作为 lambda 传递的方法,`::` 是一个方法引用 - `(k, v) -&gt; this.pAccounts(k, v)` 的语法糖。 (2认同)