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

标签 java dictionary generics 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
}

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

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

我想知道这是否是流中允许我们执行此操作的某种功能,或者是其他功能。

最佳答案

您引用的方法在 forEach(this::pAccounts) 中调用。 这是因为collect(Collectors.groupingBy(this::getKey))返回 Map .

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

所以这个forEach不是 Stream 上的方法,但是在Map上.

关于java - java中stream、collect、forEach组合的代码流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60737626/

相关文章:

c#-4.0 - 时间:2019-03-17 标签:c#genericsnew()constraints with type : (new(T))

java8 - 映射列表的列表 : check if nested list is null

Java 将对象转换为 Object[] 数组并丰富 For 循环

java - 使用 PHP 和 mysql 构建 Android 登录

c++ - map 和 unordered_map 包含指向 double 的指针?

python - 如何将列表与常见元素合并,其中这些元素本身是列​​表/元组?

java - 为什么我在代理后面对这些内容引擎的调用会失败?

java - 为什么字典初始化时不会发生内存溢出?

c++ - iso c++ 禁止声明没有类型的泛型

java - Java 泛型中的 Get-Put 原则