If you want to understand the value of lambda expressions you shouldn’t look at the only new method which has a language counterpart which existed before. How about these examples:
button.addActionListener( ev -> BACKGROUND_EXECUTOR_SERVICE.execute( () -> {
String result = longComputation();
SwingUtilities.invokeLater( () -> label.setText(result) );
});
Just think about how the equivalent pre-Java 8 code looks like and you see that the main advantage is not performance here.
If you want to look at Collection operations, how about this one?
map.merge(key, 1, Integer::sum);
This will put 1
into the map, if the key doesn’t exist in the map yet or add 1
to the value of the existing mapping otherwise. Again, think about how the old counterpart looks like. The fact that it might be even more efficient as it avoids multiple hash operations, if the map has an appropriate implementation of the method, is only an additional benefit.
Surely, the forEach
method can not provide such a big gain in expressiveness as there is the for-each language counterpart. Still, not needing to declare a loop variable can improve the source code, if the declaration requires to repeat a long type name and generic parameters. That’s especially true in the context of Map
s:
Map<ContainerOrderFocusTraversalPolicy, List<AttributedCharacterIterator>> map;
//…
map.forEach((p,l)->l.forEach(i->{ /* do your work using p and i */}));
here, this new iteration clearly wins over
for(Map.Entry<ContainerOrderFocusTraversalPolicy, List<AttributedCharacterIterator>> e:
map.entrySet()) {
ContainerOrderFocusTraversalPolicy p=e.getKey();
for(AttributedCharacterIterator i: e.getValue()) {
/* do your work using p and i */
}
}
Of course, it only matters if the actual work statements are small enough but that’s how lambda expressions should be used: to encapsulate small pieces of code. And there are still tasks which can’t be done this way and require an ordinary for-each loop, just as there are also tasks which can’t be done with a for-each loop and need the even-older for
loop dealing with an Iterator
manually…