I have two variables:
List<Basket> bigBasket = new ArrayList<>(); Basket basket = new Basket();
I wrote the following code to add a link between items in a bigBasket and basket :
for (Fruit specialFruit : bigBasket.get(0).getFruitInBasket()) { for (Fruit fruit : basket.getFruitInBasket()) { specialFruit.addRelationship(fruit); } }
Now everything is all right, but IntelliJ checked the code and suggested improving it with a method reference, so I got the following:
for (Fruit specialFruit : bigBasket.get(0).getFruitInBasket()) { basket.getFruitInBasket().forEach(specialFruit::addRelationship); }
So the above has fewer lines, but what is its actual advantage? I donβt fully understand the benefits of Java 8 features, so probably why I donβt quite understand what is happening.
In my opinion, the "improved" version of the code is not very readable in the sense of an immediate understanding of what is happening against the standard for the loop, assuming that you have little knowledge about Java 8 features.
Can someone explain the benefits of the "improved" code and standard for the loop?
EDIT: Removed invalid links to lambdas. The code just uses method references - just a ling error on my part!
source share