What is the advantage of using method references in this case?

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!

+5
source share
1 answer

I do not see the benefits in improved code in terms of performance. Both fragments will basket.getFruitInBasket() over the entire basket.getFruitInBasket() collection and perform the same action for each item.

Preference for one of the methods is simply a matter of taste. In my opinion, the version of Java 8 expresses the fact that you more clearly perform one action for all elements of the collection (assuming that you use method references).

By the way, in your code there is no lambda expression, just a reference to a method.

+6
source

Source: https://habr.com/ru/post/1213701/


All Articles