Is there any max or min function for finding the maximum or minimum in a HashSet<u32> in rust

how can i find the maximum or minimum value in a HashSet without looping through all the elements in it?

You cannot, because HashSet is by definition unordered. If you need this operation often it may be better to use another type of data structure such as BTreeSet or even a sorted Vec, depending on your other constraints.


If you never remove elements from the HashSet, you could store the maximum and minimum next to the set.

use std::collections::HashSet;

pub struct IntSet {
    set: HashSet<u32>,
    max: u32,

impl IntSet {
    pub fn new() -> Self {
        Self {
            set: HashSet::new(),
            max: 0,
    pub fn insert(&mut self, value: u32) {
        if value > self.max {
            self.max = value;
    pub fn contains(&self, value: u32) -> bool {
    pub fn get_max(&self) -> u32 {

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.