Is there an efficient and elegant way to keep the top 2 values from an iterator

Consider an arbitrary itr that returns a sequence of values.



will return max value, is there a way to return the maximum 2 values?

partialsort(collect(itr), 2) would do the trick but collect might be expensive. Wonder if there’s a elegant function to do it?

The below is the best I can think of

itr = rand(10)

res = reduce(itr, init=(-Inf, -Inf)) do (l1, l2), next_val
    next_val > l1 ? (next_val, l1) : (l1, max(next_val, l2))

all(res .== partialsort(itr, 1:2, rev=true))

here some related proposals.