Strange looking guava code

I am having problems with the code snippet below:

prices = pricesService.getProductsByCategory(category); List<Double> discountedPrices = Lists.newArrayList(Iterables.transform(prices, new Function<Double, Double>() { public Double apply(final Double from) { return from *.88; } })); 

I know what the result of the code is and it is correct in unit tests, but I am not very familiar with guava and how / why this implementation works. Also, currently it does not look safe if there is a null value in the price list? So what I need:

  • A general description of how the code works.
  • Is it safe now? If not, how can this be done?
+6
source share
2 answers

Creates a new list of doubles that are 0.88 * original.

Constructions:

Anonymous inner class

This is the way callbacks / closures sometimes execute in Java. See also the Java tutorial about this.

 new Function<Double, Double>() { public Double apply(final Double from) { return from *.88; } } 

Callback using the specified function

 Iterables.transform(prices, *func*) 

Convert result to ArrayList

The result above is Iterable , so you need to save it in the list. See Also Lists.newArrayList vs new ArrayList

 Lists.newArrayList( ... ) 
+6
source

1) Thus, Guava has static classes referenced by objects used in classes that have a conversion method that takes a collection and an instance of the guava function as variables. In this case, the developer used an anonymous function in the string, which returns a double value using the overridden "apply" method.

A more traditional implementation would be something like this:

 List<Double> discountedPrices = Lists.newArrayList(); for(Double price: prices) { discountedPrices.add(price * .88); } 

2) Not quite sure what you mean by zero security? assuming you mean what happens if the price list contains a null value? If so, guava has another solution for you in Iterables.filter (Collection, Predicate). In your case, you want to filter out zeros, and for this purpose there is a built-in guava predicate. So in your case, you can do something like:

  prices = Iterables.filter(prices, Predicates.notNull(); List<Double> discountedPrices = Lists.newArrayList( Iterables.transform(prices, new Function<Double, Double>() { public Double apply(final Double from) { return from *.88; } })); 

This first line returns a collection of prices without zeros in it, and the second will behave exactly the same as before, and you can assume that the zeros have already been deleted.

+2
source

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


All Articles