4.4.  Perform calculations using count, max, min, average and sum stream operations

[Note]

Stream data methods

Primitive streams

The stream library has specialized types IntStream, LongStream, and DoubleStream that store primitive values directly, without using wrappers. If you want to store short, char, byte, and boolean, use an IntStream, and for float, use a DoubleStream.

When you have a stream of objects, you can transform it to a primitive type stream with the mapToInt, mapToLong, or mapToDouble methods:


Stream<String> words = ...;
IntStream lengths = words.mapToInt(String::length);

					

There are methods sum(), average(), max(), and min() that return the sum, average, maximum, and minimum. These methods are defined for XxxStream and not defined for Stream:


IntStream stream = IntStream.of(2, 4, 6);
int max = stream.max().getAsInt(); // max() returns OptionalInt

stream = IntStream.of(2, 4, 6);
int min = stream.min().getAsInt(); // min() returns OptionalInt

stream = IntStream.of(2, 4, 6);
double average = stream.average().getAsDouble(); // average() returns OptionalDouble

stream = IntStream.of(2, 4, 6);
int sum = stream.sum(); // sum() returns int

System.out.println("max : " + max);
System.out.println("min : " + min);
System.out.println("average : " + average);
System.out.println("sum : " + sum);

					

max : 6
min : 2
average : 4.0
sum : 12
					

Professional hosting         Exam 1Z0-817: Upgrade OCP Java 6, 7 & 8 to Java SE 11 Developer Quiz     Exam 1Z0-810: Upgrade to Java SE 8 Programmer Quiz