java 中 stream、collect 和 forEach 组合的代码流
Code flow with the combination of stream, collect and forEach in java
我在公司项目中遇到过这样的代码
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))
returns一个Map
.
Map
上的 forEach
,根据 javadoc,接受一个 BiConsumer<? super K,? super V>
,其中第一个参数是类型 K
的键和second - V
类型的值。
所以这个 forEach
不是 Stream
上的方法,而是 Map
.
上的方法
我在公司项目中遇到过这样的代码
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))
returns一个Map
.
Map
上的 forEach
,根据 javadoc,接受一个 BiConsumer<? super K,? super V>
,其中第一个参数是类型 K
的键和second - V
类型的值。
所以这个 forEach
不是 Stream
上的方法,而是 Map
.