4.4.  Perform calculations by using Java Stream methods, such as count(), max(), min(), average(), and sum()

[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, 1, 34, 5, 9);
int max = stream.max().getAsInt(); // max() returns OptionalInt

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

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

stream = IntStream.of(2, 4, 6, 1, 34, 5, 9);
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 : 34
min : 1
average : 8.714285714285714
sum : 61
					

Professional hosting         Free 'Oracle Certified Expert Web Services Developer 6' Guide     Exam 1Z0-810: Upgrade to Java SE 8 Programmer Quiz