108. Iterator::max_by_key — Find the Biggest Without Sorting the Whole Thing
Need the longest string in a Vec? Don’t sort the whole list to grab the last element — max_by_key walks once, allocates nothing, and returns it directly.
The wasteful way
You want the longest word from a list. The first instinct is often to sort and pick:
| |
That’s O(n log n) work — and a side effect, since your Vec is now reordered — just to answer “which one is biggest?”.
Enter max_by_key
max_by_key walks the iterator once, tracks the running maximum, and hands you the element it picked:
| |
O(n), no allocation, no mutation. The original Vec is untouched and you get a &&str back without cloning anything.
Same energy: min_by_key
The mirror method is just as useful — find the shortest word in one pass:
| |
Picking by computed value
The closure can do real work — compute distance, score, age — anything that returns something Ord:
| |
No need to sort, no need to implement Ord on the struct — just point at the field that decides.
Tiebreaks: last one wins
When two elements share the same key, max_by_key returns the last one and min_by_key returns the first:
| |
Worth knowing if your data has duplicates — pick the iteration direction so the right element wins.
When to reach for it
If you catch yourself sorting and then grabbing first(), last(), or [0], stop. min_by_key and max_by_key are the targeted tools: one pass, zero allocations, and the result type is exactly the element you wanted.