带有流,collect和forEach的组合的代码流

问题描述 投票:1回答:1

我在我的公司项目中遇到了这样的代码,>]

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

我曾尝试在网上找到类似的示例,但未找到与此行为相匹配的内容。

我想知道这是否是流中的某种功能,使我们能够做到这一点,或者是其他方式。

我在我的公司项目中遇到了代码,就像这个空pAccount(List account){account.stream().filter(o-> getKey(o)!= null).collect(...

java dictionary java-stream core
1个回答
2
投票

您要引用的方法在forEach(this::pAccounts)中调用。这是因为collect(Collectors.groupingBy(this::getKey))返回Map,而forEach上的Map根据javadoc取了BiConsumer<? super K,? super V>,其中第一个参数是K类型的键,第二个-类型的值V。因此,此forEach不是Stream的方法,而是Map的方法。

© www.soinside.com 2019 - 2024. All rights reserved.