Is there a concise way to extract both the min and max value of a stream (based on some comparator) in one pass?
There appear to be many ways to get the min and max values individually, or I can sort the stream into a temporary object, for example:
List<T> sorted = Stream.of(...).sorted().collect(Collectors.toList()); T min = sorted.get(0); T max = sorted.get(sorted.size() - 1);
But this isn't concise and requires allocating a temporary object. I'd rather not allocate a temporary object or make two passes through the stream. Is there an alternative?
Pair<T> extent = Stream.of(...).???
With the introduction of Stream with Java 8, we can convert the array into the corresponding type stream using the Arrays. stream() method. Then we can call the max() and min() method, which returns the maximum and minimum element of this stream as OptionalInt .
min method we get the minimum element of this stream for the given comparator. Using Stream. max method we get the maximum element of this stream for the given comparator. The min and max method both are stream terminal operations.
We can find Maximum and Minimum using simply iterate the HashSet and maintain the min and max variable and update it accordingly while traversing through each element and comparing it with the min and max values.
Calling stream() method on the list to get a stream of values from the list. Calling mapToInt(value -> value) on the stream to get an Integer Stream. Calling max() method on the stream to get the max value. Calling orElseThrow() to throw an exception if no value is received from max()
The summarizingInt
collector works well if you have a Stream of Integers.
IntSummaryStatistics stats = Stream.of(2,4,3,2) .collect(Collectors.summarizingInt(Integer::intValue)); int min = stats.getMin(); int max = stats.getMax();
If you have doubles you can use the summarizingDouble
collector.
DoubleSummaryStatistics stats2 = Stream.of(2.4, 4.3, 3.3, 2.5) .collect(Collectors.summarizingDouble((Double::doubleValue)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With