The Stream interface is a generic type of interface and is useful for many types of problems. When a stream needs to be used with a primitive, a lot of boxing and unboxing is required. As a result, when a large amount of data needs to be processed, using the Stream interface may not be the best solution. To address this problem, several stream interfaces designed to work with primitive data have been provided. These include: IntStream, LongStream and DoubleStream. These are often returned when mapping from a generic class to a primitive data type. Several functional interfaces have been added to support this type of conversion including ToIntFunction, IntConsumer, and IntSupplier. Other primitive stream interfaces, such as for boolean and short, were not added. It was felt that the three primitive streams were adequate and other primitives could be addressed using other techniques. Primitive stream interfaces possess a number of common operations including, among others: – count – sum – min
– max – mean There is also the IntSummaryStatistics class that provides summary statistics on a stream of integers. In addition, there are corresponding DoubleSummaryStatistics and LongSummaryStatistics classes.
Using the IntStream Interface The IntStream interface supports operations using integers and possesses a number of useful methods. The following illustrates an implicit use of the IntStream interface. A stream of parts is created and the mapToInt method is applied against this. This will return an IntStream object. The sum method is then applied to the new primitive stream and returns the sum of the weights of all of the parts in the stream. Stream<Part> partsStream = partsList.stream(); int sumOfWeights = partsStream.mapToInt( (Part p) -> p.getWeight()).sum(); System.out.println(“Sum: ” + sumOfWeights); The output will be as follows: Sum: 9 The following explicitly uses an IntStream to achieve the same results: IntStream tmpStream = partsStream.mapToInt(
(Part p) -> p.getWeight()); System.out.println(“Sum: ” + tmpStream.sum());