Hi guys!
Do you still not use Lambdas in Java? Today I will show you how event-based projects can benefit from them.
Nice small listeners
Lambdas could be considered as a handy replacement for anonymous classes. Vaadin is an event-based framework. So, before Java 8 our PIM project had tons of code like this:
button.addClickListener(new Button.ClickListener() { private static final long serialVersionUID = -8692988480268369082L; public void buttonClick(ClickEvent event) { layout.addComponent(new Label("Thank you for clicking")); } });
Note, how much clearer the code is when it uses a Lambda expression instead of the anonymous class:
button.addClickListener(event -> layout.addComponent(new Label("Thank you for clicking")));
The following unnecessary code was removed:
new
keyword together with the listener interface nameserialVersionUID
field- the single interface method declaration
Even if a listener method has several lines, it also looks good:
button.addClickListener(event -> { Label label = new Label("Thank you for clicking"); layout.addComponent(label); });
Another benefit of Lambdas is direct access to parent class fields without adding parent class name before this
keyword like:
this.field
Instead of
MyClass.this.field
Eclipse trick
Eclipse has a useful shortcut to automatically convert similar anonymous classes into Lambda expressions. For this purpose do the following:
1. Delete the serialVersionUID
line. Note, the listener interface name is underlined as a warning.
2. Place the keyboard cursor on the listener interface name and press Ctrl+1
3. In the appeared popup menu select Convert to lambda expression
Lambdas in Stream API
Another useful application of Lambda expressions is Stream API. It is a kind of replacement for iterators. Streams are especially useful if you need to do many sequential manipulations on Collection items or process big Collections effectively.
Below is a simplified example from the PIM project code that represents a list of Entity objects as a String. The code does the following steps:
- Retains only entities from the Master catalog
- Sorts entities by ID
- Forms String representation for each Entity object
- Concatenates all Entity String representations into one String like 1@1,3@1,7@1
String result = entityList.stream() .filter(entity -> MASTER.equals(entity.getCatalogId())) .sorted(Comparator.comparing(Entity::getId)) .map(entity -> entity.getId() + AT + entity.getCatalogId()) .collect( Collectors.joining( COMMA ) );
Think how much more code it would require to do the same with usual for
operator.
I hope I persuaded you to learn a bit more about Lambda expressions and start using them in your applications.
bye!