Primitive Type Stream Examples

In addition to Stream, java.util.stream package also provide a set of primitive type Streams such as DoubleStream, IntStream and LongStream. The primitive type streams are pretty similar with Stream. In this post I will use the IntStream to illustrate how to use primitive type streams.

Create an IntStream

From integer array:

IntStream stream = IntStream.of(2, 4, 6, 1, 5, 9);

From a stream of Strings:

Stream<String> stream = Stream.of("abcd", "abcdef", "ab");
IntStream intStream = stream.map(s -> s.length()).mapToInt(Integer::new);

Basic Methods

In addition to methods in Stream, IntStream also have more methods designed for manipulating integers. Here are some of them:

int max1 = stream.max().getAsInt();
int min1 = stream.min().getAsInt();
double average = stream.average().getAsDouble();
IntStream distinctStream = stream.distinct();

IntSummaryStatistics

IntSummaryStatistics is a class for collecting statistics such as count, min, max, sum, and average.

IntSummaryStatistics iss = stream.summaryStatistics();
double average = iss.getAverage();
long count = iss.getCount();
int max = iss.getMax();
int min = iss.getMin();
long sum = iss.getSum();

Reference:
1. IntSummaryStatistics
2. IntStream

Leave a Comment