Java Reference
In-Depth Information
Listing 5.8. Find the transaction with the smallest value
You can do better. A stream supports the methods min and max that take a Comparator as
argument to specify which key to compare with when calculating the minimum or maximum:
Optional<Transaction> smallestTransaction =
transactions.stream()
.min(comparing(Transaction::getValue));
5.6. Numeric streams
You saw earlier that you could use the reduce method to calculate the sum of the elements of a
stream. For example, you can calculate the number of calories in the menu as follows:
int calories = menu.stream()
.map(Dish::getCalories)
.reduce(0, Integer::sum);
The problem with this code is that there's an insidious boxing cost. Behind the scenes each
Integer needs to be unboxed to a primitive before performing the summation. In addition,
wouldn't it be nicer if you could call a sum method directly as follows?
int calories = menu.stream()
.map(Dish::getCalories)
.sum() ;
But this isn't possible. The problem is that the method map generates a Stream<T>. Even
though the elements of the stream are of type Integer, the Streams interface doesn't define a
sum method. Why not? Say you had only a Stream<Dish> like the menu; it wouldn't make any
sense to be able to sum dishes. But don't worry; the Streams API also supplies primitive stream
specializations that support specialized methods to work with streams of numbers.
 
Search WWH ::




Custom Search