java - How does Stream.max() handle equality? -


although suspect answer "it's not specified"...

if there multiple "greatest/lowest" elements in stream comparator passed max or min methods considers equal (returns 0), specified somewhere element found?

after reading source code, think should first greatest element found according collection order. can check out source code of stream.max(comparator<? super t> comparator), implementation class referencepipeline.max

    @override     public final optional<p_out> max(comparator<? super p_out> comparator) {         return reduce(binaryoperator.maxby(comparator));     } 

that can see, when call stream.max, mean call stream.reduce(binaryoperator<p_out> accumulator)

and @ source code of binaryoperator.maxby(comparator)

    public static <t> binaryoperator<t> maxby(comparator<? super t> comparator) {         objects.requirenonnull(comparator);         return (a, b) -> comparator.compare(a, b) >= 0 ? : b;     } 

it's clear, when a equals b, returns a. when there multiple "greatest/lowest" elements in stream, "greatest/lowest" element should first "greatest/lowest" element according collection order

there example @ blew, reference.

        list<student> list = arrays.aslist(new student("s1", 1), new student("s2", 5), new student("s3", 3), new student("s4", 5));         // should student of 's2'         list.stream().max(comparator.comparing(student::getscore));         // should student of 's4'         list.stream().reduce((a, b) -> comparator.comparing(student::getscore).compare(a, b) > 0 ? : b); 

Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -