Another advantage of lambdas (and method references) is seen when combining them with the Stream API and other functions added in Java 8, for example. Not necessary.
Consider this code:
private void pushToFront(AbstractInfo contactInfo) { registeredWindows.stream() .filter(window -> window.getWindowId() == contactInfo.getId()) .findAny() .ifPresent(Window::pushToFront); }
The method filters the list of registered windows corresponding to the window, with the contact identifier returning optional. If the list contains a window with a matching identifier, then the value Optional is present, and then the pushToFront method will be pressed on it. Compare this with the same functionality written in Java 7:
private void pushToFront(AbstractInfo contactInfo) { for (Window window : registeredWindows) { if (window.getWindowId() == contactInfo.getId() { window.pushToFront(); } } }
Code with a lambda expression, a thread reference, and a method, at least for me, is more concise and readable (when you use streaming). The above example is pretty simple, but consider one that in Java 7 requires nested loops, multiple conditional statements, etc. It is not easy to read even more difficult, so as not to lose information about what is happening.
Lambdas makes full use of other neat Java 8 features that, among other things, provide neat, clean, efficient, and clear code.
On the bottom line, you should consider lambda expressions as part of a larger whole that are big for yourself, but even better when combined with other Java 8 building blocks.
ttarczynski
source share