4

Пусть есть IntStream, возможно ли получить из него допустим массив или лист, в котором будут 2 значения min и max стрима? Либо можно ли вообще каким-то образом вызвать терминальный метод на стрим больше 1 раза?

4 ответа 4

11
IntSummaryStatistics stats = IntStream.range(1, 100)
                                      .summaryStatistics();

int min = stats.getMin();
int max = stats.getMax();
4
  • Да, так тоже можно :) 3 апр 2018 в 22:34
  • пустой stream покажет min = 2147483647, а max = -2147483648:) надо выполнить проверку min <= max, чтобы убедится, что steam не пустой, что есть из чего выбирать и min и max
    – Sergey
    4 апр 2018 в 2:01
  • 4
    Зачем min<=max, если есть getCount()?
    – vp_arth
    4 апр 2018 в 3:31
  • @vp_arth Действительно можно. Не подумал, что может быть getCount. Так же как не подумал о том, что для извлечения только лишь min и max, можно попутно насобирать и кучу другой, бесполезной в данном случае, статистики:) Хотя это может быть даже оптимальнее, быстрее самодельного collec. Кто знает, кто знает...
    – Sergey
    5 апр 2018 в 8:18
3

Можно создать коллектор, находящий минимальный и максимальный элемент. Вообще рекомендую способ с IntSummaryStatistics, но коллектор можно сделать. Коллектор:

static<T, R> Collector<T, ?, Optional<R>> minMax(
        Comparator<? super T> comparator,
        BiFunction<? super T, ? super T, ? extends R> finisher){

    class Accumulator{
        T min;
        T max;

        boolean present;

        void add(T value){
            if(present){
                if(comparator.compare(value, min) <0) min= value;
                if(comparator.compare(value, max) >0) max= value;

            }else {
                min=max=value;
                present=true;
            }
        }

        Accumulator combiner(Accumulator other){
            if(!other.present) return this;
            if(!present) return other;
            if(comparator.compare(other.min, min) <0) min=other.min;
            if(comparator.compare(other.max, max) >0) max=other.max;
            return this;
        }


    }

    return Collector.of(Accumulator::new,
            Accumulator::add,
            Accumulator::combiner,
            accumulator -> accumulator.present
                    ? Optional.of(finisher.apply(accumulator.min, accumulator.max))
                    : Optional.empty());
}

Его использование может выглядит вот так:

Integer [] arr= IntStream.of(12, 45, 23, 68).
            boxed().
            collect(
                    minMax(
                            Integer::compareTo, (min, max) -> new Integer[] {min, max})).get();
    for (Integer i: arr) {
        System.out.println(i);
    }

Можно сделать чтоб возвращал List:

List<Integer> list =IntStream.of(12, 45, 23, 68).
            boxed().
            collect(
                    minMax(
                            Integer::compareTo, (min, max) -> Arrays.asList(min, max))).get();

    list.iterator().forEachRemaining(System.out::println);
2

Нет, стрим позволяет пройтись по нему только один раз (а если нижележащий сплитератор выстрелит, то можно и вообще не дойти до конца). Но это не значит, что вы не можете одновременно собирать и максимум, и минимум:

private static class Result {
    private Integer minimum;
    private Integer maximum;

    public Integer getMinimum() {
        return minimum;
    }

    public Integer getMaximum() {
        return maximum;
    }

    public synchronized Result update(int value) {
        if (minimum == null || minimum > value) {
            minimum = value;
        }
        if (maximum == null || maximum < value) {
            maximum = value;
        }
        return this;
    }

    public synchronized void combine(Result other) {
        if (other.getMinimum() != null) {
            update(other.getMinimum());
        }
        if (other.getMaximum() != null) {
            update(other.getMaximum());
        }
    }

    @Override
    public String toString() {
        return "Result {minimum=" + minimum + ", maximum=" + maximum + "}";
    }
}

public static Result compute(IntStream stream) {
    return stream.collect(Result::new, Result::update, Result::combine);
}
3
  • Да, так то можно, имел ввиду чтобы одним стримом и без доп методов. Спасибо за инфу! 3 апр 2018 в 22:28
  • IntStream разве имеет reduce такой сигнатуры? там ведь только int reduce(...) и OptionalInt reduce(...) ничего типа <R> reduce(...) вроде нет
    – Sergey
    4 апр 2018 в 2:10
  • @Sergey почему-то думал, что у всех стримов сигнатуры совпадают, обновил, спасибо
    – etki
    4 апр 2018 в 6:46
1

Вот Ваш массив:

int[] miniMax = IntStream.range(1, 11).collect(() -> {
    return new int[] { Integer.MAX_VALUE, Integer.MIN_VALUE };
}, (t, value) -> {
    if (t[0] > value) t[0] = value;
    if (t[1] < value) t[1] = value;
}, (t, u) -> {
    if (t[0] > u[0]) t[0] = u[0];
    if (t[1] < u[1]) t[1] = u[1];
});

int min = miniMax[0];
int max = miniMax[1];

Если попадётся пустой stream, то получится невероятный результат min == 2147483647 и max == -2147483648

Условие, что получено именно то, что надо: min <= max

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.