Max and Min elements

Report a typo

The following code snippets contains a method for finding min and max elements of a stream in accordance with a given comparator. The stream elements are of generic type T, and the given Comparator<? super T> order is used to find the minimum and maximum.

After you find the minimum and maximum elements, you should pass them to minMaxConsumer in the following way:

minMaxConsumer.accept(min, max);
Fill in the gaps with the relevant elements
import java.util.*;
import java.util.function.*;
import java.util.stream.*;

class MinMax {

    public static <T> void findMinMax(
            Stream<? extends T> stream,
            Comparator<? super T> order,
            BiConsumer<? super T, ? super T> minMaxConsumer) {

        var  = new MutableContainer<T>();
        
        stream.(element -> {
            T min = state.;
            if ( == null || order.compare(, min)  0) {
                 = element;
            }
            T max = state.;
            if ( == null || order.compare(element, max)  0) {
                 = element;
            }
        });
        minMaxConsumer.accept(state.minimum, state.maximum);
    }
}

// A class that helps us hold mutable values during stream processing.
class MutableContainer<T> {
    T minimum;
    T maximum;
}
element<maximumminmaxforEach==orderstate.minimumminimum>statestate.maximum

Create a free account to access the full topic