Better way to find unique values?

I wrote a function that takes as input a vector of structs and returns a vector of unique strings:

fn filter_uniq(vec: Vec<CourseRequirements>) -> Vec<String> {
    let mut uniq = vec
        .into_iter()
        .map(|course| course.CRS_PREREQ)
        .collect::<Vec<String>>();

    uniq.sort();
    uniq.dedup();
    uniq
}

Is there a simpler/more concise way to write this?

1 Like

You could collect into a HashSet to dedup instead:

fn filter_uniq(vec: Vec<CourseRequirements>) -> Vec<String> {
    vec.into_iter()
        .map(|course| course.CRS_PREREQ)
        .collect::<HashSet<_>>()
        .into_iter()
        .collect()
}
9 Likes

I would just keep it as a HashSet instead of converting back to a Vec<String>. That way you can keep constant time lookups.

5 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.