JetBrains Academy: Functional data processing with streams - Kamil-Jankowski/Learning-JAVA GitHub Wiki

JetBrains Academy: Functional data processing with streams

Finding max and min elements:

Implement a method for finding min and max elements of a stream in accordance with a given comparator.

The found elements pass to minMaxConsumer in the following way:

minMaxConsumer.accept(min, max);

If the stream doesn't contain any elements, invoke:

minMaxConsumer.accept(null, null);

public static <T> void findMinMax(
        Stream<? extends T> stream,
        Comparator<? super T> order,
        BiConsumer<? super T, ? super T> minMaxConsumer) {
    
    // your implementation here
    Deque<T> sortedElements = stream.sorted(order).collect(Collectors.toCollection(ArrayDeque::new));
    
    if (sortedElements.isEmpty()) {
        minMaxConsumer.accept(null, null);
    } else {
        T min = sortedElements.pollFirst();
        T max = sortedElements.pollLast();
    
        minMaxConsumer.accept(min, max);
    }

or

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

    // your implementation here
    List<T> fromStream = stream.collect(Collectors.toList());

    if (fromStream.isEmpty()) {
        minMaxConsumer.accept(null, null);
    } else {
        T min = fromStream.stream().min(order).get();
        T max = fromStream.stream().max(order).get();

        minMaxConsumer.accept(min, max);
    }
    
}

⚠️ **GitHub.com Fallback** ⚠️