![]() | |
|
Stream
data methods
Stream.min(...)
and Stream.max(...)
The min(...)
and max(...)
methods are Stream
terminal operations. Once these are
called, the stream will be iterated, filtering and mapping applied, and the minimum or maximum value in the stream will
be returned.
Here is a Java Stream.min(...)
example:
String shortest = items.stream() .min(Comparator.comparing(item -> item.length())) .get();
The min(...)
and max(...)
methods return an Optional
instance which has
a get()
method, which you use to obtain the value. In case the stream has no elements the
get()
method will throw NoSuchElementException
.
The Stream.min(...)
and Stream.max(...)
methods take a Comparator
interface as
parameter. The Comparator.comparing(...)
method creates a Comparator
based on the lambda
expression passed to it. In fact, the comparing(...)
method takes a Function
which is a
functional interface suited for lambda expressions. It takes one parameter and returns a value.
Stream.count()
The Stream.count()
method simply returns the number of elements in the stream after filtering has been applied.
Here is an example:
long count = items.stream() .filter(item -> item.startsWith("J")) .count();
This example iterates the stream and keeps all elements that start with the character J
, and then
counts these elements.
The count()
method returns a long
which is the count of elements in the stream.
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
![]() ![]() ![]() |