'finding the maximum in a HashSet<u32> in rust? [closed]

how can i find the maximum or minimum value in a HashSet without looping through all the elements in it? Is there any function or one liner way to do so ?



Solution 1:[1]

You can do something like this:

let hs: HashSet<u32> = HashSet::from_iter(vec![54, 23, 55, 6, 3, 100]);
let min_value = *hs.iter().min().unwrap();
let max_value = *hs.iter().max().unwrap();

That way you won't have to loop yourself, but internally that's exactly what is going to happen. It's not possible to find the min or max value in a hash set (or a hash map, for that matter), without checking all the values.

BTW there is another (relatively common) set type, BTreeSet, which keeps its values ordered. That would allow you to simply get the first or the last element (via iter().next() or iter().next_back()) and you've got you min/max value w/o any extra work. Performance-wise that would be much faster of course.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1