fadedbee
fadedbee

Reputation: 44725

Idiomatic way of getting the key of the largest value in a BTreeMap?

I need to get get the key associated with the largest value in a BTreeMap. (Doing this the other way around is simple.)

My attempt so far is:

let mut opt_pair: Option<(&Foo, u32)> = None; 
for (key, value) in my_btreemap { // my_btreemap is known to be non-empty
    match opt_pair {
        Some(pair) => {
            if value > pair.1 {
                opt_pair = Some((key, value)); 
            }
        },
        None => {
            opt_pair = Some((key, value)); 
        }
    }
}

opt_pair.unwrap().0

Is there an idiomatic way of doing this, in a more functional style?

Upvotes: 2

Views: 900

Answers (1)

Schwern
Schwern

Reputation: 164799

Use iter to get an Iterator of each pair. Then call max_by_key on the iterator; this takes a closure to get the thing to compare.

let opt_pair = map
    .iter()                   // get an iterator over the tree
    .max_by_key( |p| p.1 )    // check the value of each pair for the max
    .unwrap();                // unwrap the result

println!("key: {}, value: {}", opt_pair.0, opt_pair.1);

Upvotes: 4

Related Questions