Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concise way to get both min and max value of Java 8 stream

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(...).??? 
like image 356
Mzzzzzz Avatar asked Jan 23 '17 21:01

Mzzzzzz


People also ask

How do you find the maximum and minimum value of an array in Java 8?

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 .

How do you use max and min in stream?

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.

How do you find the max and min in Java?

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.

How do I find the maximum element in a stream list?

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()


1 Answers

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))); 
like image 76
Will Humphreys Avatar answered Sep 20 '22 18:09

Will Humphreys