Java Reference ยท Streams and Functional
Java Stream count(), min() and max()
Reference for Java Stream.count(), min() and max(): count elements, find the smallest or largest with a Comparator, and handle the Optional result.
count(), min() and max() are terminal operations: they consume the stream and produce a single answer. count() returns the number of elements as a long. min(comparator) and max(comparator) return the smallest or largest element according to a Comparator, wrapped in an Optional because an empty stream has no answer.
Primitive streams (IntStream, LongStream, DoubleStream) have their own min() and max() that need no comparator and return OptionalInt, OptionalLong or OptionalDouble.
long n = Stream.of("a", "b", "c").count(); // 3 Optional<String> longest = words.stream() .max(Comparator.comparingInt(String::length));
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
long count() Optional<T> min(Comparator<? super T> comparator) Optional<T> max(Comparator<? super T> comparator)
| Name | Description |
|---|---|
comparator |
Defines the ordering. Use Comparator.naturalOrder(), Comparator.comparing(...) or Integer::compare. Must not be null. |
Returns: count() returns a long. min() and max() return an Optional<T>, empty when the stream is empty.
Throws: NullPointerException from min()/max() if the selected element is null, because an Optional cannot hold null.
Usage notes
count()and elements: since Java 9,count()may skip running the pipeline when the size is known from the source and no operation changes it. Side effects inpeek()ormap()then may not run. Do not rely on side effects inside a pipeline that ends incount().- Large counts: the result is a
long; it does not overflow likeCollection.size()(anint). - Ties: when several elements compare equal, both
min()andmax()return the first one in encounter order (the second example shows it). Do not depend on this in parallel code. - Both extremes at once: a stream can be consumed only once. For min and max together use
IntSummaryStatisticsor aCollectors.teeing()collector. - Comparator mistakes:
max()withComparator.reverseOrder()returns the smallest element. Pick the direction deliberately. - Complexity: all three are a single pass, O(n);
min/maxdo not sort. - Counting by group: use
Collectors.groupingBy()withcounting().
Related
stream-match,stream-find,stream-reduce,IntSummaryStatistics- Lessons: Streams, Optional