Numeric stream #
In addition to the interface Stream, Java 8 introduced the interface IntStream (resp. DoubleStream, LongStream) that represents a stream of (unboxed) int (resp. long, double).
It provides native methods such as (sum and average) that are not available for the types Stream<Integer> (resp. Stream<Double>, Stream<Long>).
Conversion #
Warning. The interface
IntStream(resp.DoubleStream,LongStream) does not extend the interfaceStream.
A instance of Stream<$T$> can be converted to an instance of IntStream (resp. DoubleStream, LongStream) with the instance method Stream.mapToInt.
This method takes as argument a callback method of type
$\qquad T \to$ int
that converts each element of the stream to an int.
Example.
The following method converts a list of cities into an
IntStreamthat contains their zip codes.IntStream extractZipCodes(List<City> cities){ return cities.stream() .mapToInt(c -> c.zipCode); }