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

**URL:** https://discourse.julialang.org/t/is-there-an-efficient-and-elegant-way-to-keep-the-top-2-values-from-an-iterator/77121
**Category:** General Usage
**Created:** [February 26, 2022, 1:34pm UTC](https://discourse.julialang.org/t/is-there-an-efficient-and-elegant-way-to-keep-the-top-2-values-from-an-iterator/77121 "2022-02-26T13:34:24Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![xiaodai](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/xiaodai/32/15937_2.png) [@xiaodai](https://discourse.julialang.org/u/xiaodai)
#### Post date: [February 26, 2022, 1:34pm UTC](https://discourse.julialang.org/t/is-there-an-efficient-and-elegant-way-to-keep-the-top-2-values-from-an-iterator/77121/1 "2022-02-26T13:34:25Z")

</div>

Consider an arbitrary `itr` that returns a sequence of values.

Now

```julia
maximum(itr)

```

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

```julia
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))
end

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

```

---

<div class="post-metadata">

### Author: ![rocco\_sprmnt21](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rocco_sprmnt21/32/20127_2.png) [@rocco\_sprmnt21](https://discourse.julialang.org/u/rocco_sprmnt21)
#### Post date: [February 26, 2022, 2:16pm UTC](https://discourse.julialang.org/t/is-there-an-efficient-and-elegant-way-to-keep-the-top-2-values-from-an-iterator/77121/2 "2022-02-26T14:16:05Z")

</div>

[here](https://discourse.julialang.org/t/the-quasi-best-maxn-function/52813/13) some related proposals.
