3 ms·
To be fair, there are only 3 signatures for the forEach() method, the reason that section is so noisy is because it's followed by forEachEntry(), forEachKey(),
by openasocket 10y ago
To be fair, there are only 3 signatures for the forEach() method, the reason that section is so noisy is because it's followed by forEachEntry(), forEachKey(), and forEachValue(), each of which has two signatures. You technically don't need those other methods, but they are convenient to have. I find "map.forEachValue(1, Foo::bar)" to be more clear than "map.forEach(1, (_, v) -> Foo.bar(v))".
Manual composition can get ugly if the argument is used multiple times, especially if the function is non trivial. Say something like
map.forEach(1, Expensive::func, x -> x * x)
which would naively manually compose to
map.forEach(1, (k, v) -> Expensive.func(k, v) * Expensive.func(k, v))
which is going to be less efficient, doubly bad if that function has side effects, and noisy on top of it. You could assign the value to a local variable inside the lambda, which gives you
map.forEach(1, (k, v) -> { int x = Expensive.func(k, v); return x * x; })
which fixes the efficiency and correctness problems, but is a bit too verbose for me. There's probably other situations, that was just the first one I thought of.
Honestly, though, it all comes down to taste and the situation. I personally would use manual composition excepting circumstances like my example above.