Code flow with the combination of stream, collect and forEach in java

Viewed 172

I have come across code in my companies project, which goes like this

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
}

While debugging we came to the conclusion that pAccount(List<Account> accounts) calls pAccounts(Key key , List<Account> accounts.

I have tried to find similar examples online but found nothing that matches this behavior.

I want to know if this is some kind of functionality in streams that allows us to do that or it's something else.

1 Answers

The method you're referring to is called in forEach(this::pAccounts). It's because collect(Collectors.groupingBy(this::getKey)) returns a Map.

The forEach on Map, according to javadoc, takes a BiConsumer<? super K,? super V>, where the first parameter is the key of type K and the second - a value of type V.

So this forEach is not a method on Stream, but on Map.

Related