std-method

Iterator::max_by_key — choose largest key

Return the item with the greatest computed key; ties choose the last such item. Unlike sorting, selecting a single extremum does not require sorting all input. Expected stdout (not executed): Some(("C", 9)) Common mistake: Expecting the first item when keys tie.

Formal Syntax & Structure

rust syntaxrust
fn max_by_key<B, F>(self, f: F) -> Option<Self::Item> where Self: Sized, B: Ord, F: FnMut(&Self::Item) -> B

Working Example

Example Snippetrust
fn main() {    let top = [("A", 7), ("B", 9), ("C", 9)].into_iter().max_by_key(|p| p.1);    println!("{top:?}");}
Rust Reference