Java Reference
In-Depth Information
5.6.1. Primitive stream specializations
Java 8 introduces three primitive specialized stream interfaces to tackle this issue, IntStream,
DoubleStream, and LongStream, that respectively specialize the elements of a stream to be int,
long, and double—and thereby avoid hidden boxing costs. Each of these interfaces brings new
methods to perform common numeric reductions such as sum to calculate the sum of a numeric
stream and max to find the maximum element. In addition, they have methods to convert back
to a stream of objects when necessary. The thing to remember is that these specializations aren't
more complexity about streams but instead more complexity caused by boxing—the
(efficiency-based) difference between int and Integer and so on.
Mapping to a numeric stream
The most common methods you'll use to convert a stream to a specialized version are mapToInt,
mapToDouble, and mapToLong. These methods work exactly like the method map that you saw
earlier but return a specialized stream instead of a Stream<T>. For example, you can use
mapToInt as follows to calculate the sum of calories in the menu:
Here, the method mapToInt extracts all the calories from each dish (represented as an Integer)
and returns an IntStream as the result (rather than a Stream<Integer>). You can then call the
sum method defined on the IntStream interface to calculate the sum of calories! Note that if the
stream were empty, sum would return 0 by default. IntStream also supports other convenience
methods such as max, min, and average.
Converting back to a stream of objects
Similarly, once you have a numeric stream, you may be interested in converting it back to a
nonspecialized stream. For example, the operations of an IntStream are restricted to produce
primitive integers: the map operation of an IntStream takes a lambda that takes an int and
produces an int (an IntUnaryOperator). But you may want to produce a different value such as a
Dish. For this you need to access the operations defined in the Streams interface that are more
general. To convert from a primitive stream to a general stream (each int will be boxed to an
Integer) you can use the method boxed as follows:
 
Search WWH ::




Custom Search