How does Stream.max() handle equality?

前端 未结 2 535
故里飘歌
故里飘歌 2020-12-18 20:50

Although I suspect the answer to be \"It\'s not specified\"...

If there are multiple \"greatest/lowest\" elements in a Stream which the Comparator

2条回答
  •  借酒劲吻你
    2020-12-18 20:56

    After reading the source code, I think should be the first greatest element will be found according to the collection order. We can check out the source code of the Stream.max(Comparator comparator), the implementation class is ReferencePipeline.max

        @Override
        public final Optional max(Comparator comparator) {
            return reduce(BinaryOperator.maxBy(comparator));
        }
    

    that you can see, when you call the Stream.max, you mean call the Stream.reduce(BinaryOperator accumulator)

    And look at the source code of BinaryOperator.maxBy(comparator)

        public static  BinaryOperator maxBy(Comparator comparator) {
            Objects.requireNonNull(comparator);
            return (a, b) -> comparator.compare(a, b) >= 0 ? a : b;
        }
    

    It's clear, when a equals b, it returns a. So when there are multiple "greatest/lowest" elements in a Stream, the "greatest/lowest" element should be the first "greatest/lowest" element according to the collection order

    There is a example at blew, just for your reference.

            List list = Arrays.asList(new Student("s1", 1), new Student("s2", 5), new Student("s3", 3), new Student("s4", 5));
            // it should be student of 's2'
            list.stream().max(Comparator.comparing(Student::getScore));
            // it should be student of 's4'
            list.stream().reduce((a, b) -> Comparator.comparing(Student::getScore).compare(a, b) > 0 ? a : b);
    

提交回复
热议问题