HashSet
- Rust course
- Intermediate
- Lesson 56/115
- 4 min
Build a set of unique elements with HashSet.
HashSet
HashSet<T> is a set keeping only one of each value. It's used to remove duplicates and answer "is this present?" quickly:
use std::collections::HashSet;
let mut gorulen = HashSet::new();
println!("{}", gorulen.insert("ali")); // true: new
println!("{}", gorulen.insert("ali")); // false: already there
println!("{}", gorulen.contains("ece")); // falseSince insert returns a bool, the "have I seen this before?" check fits in one line.
Set operations
Set operations return iterators of references; the result must be collected or counted. A HashSet is unordered too, so sort before printing:
let a: HashSet<i32> = [1, 2, 3, 4].into_iter().collect();
let b: HashSet<i32> = [3, 4, 5].into_iter().collect();
let mut ortak: Vec<i32> = a.intersection(&b).copied().collect();
ortak.sort();
println!("{:?} {}", ortak, a.union(&b).count()); // [3, 4] 5If you need a sorted set, use BTreeSet.
Practice Common elements
Create two HashSets from the arrays [1, 2, 3, 4] and [3, 4, 5]. Collect the intersection into a sorted vector; print the vector and the number of elements in the union separated by a space.
Starter code
use std::collections::HashSet;
fn main() {
// buraya yaz
}Sample solution
use std::collections::HashSet;
fn main() {
let a: HashSet<i32> = [1, 2, 3, 4].into_iter().collect();
let b: HashSet<i32> = [3, 4, 5].into_iter().collect();
let mut ortak: Vec<i32> = a.intersection(&b).copied().collect();
ortak.sort();
println!("{:?} {}", ortak, a.union(&b).count());
}Expected output
[3, 4] 5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does <code>a.intersection(&b)</code> give?
- Only those in a
- All elements
- Those in neither
- Elements present in both sets Correct answer
Explanation: union is the union, difference the difference, symmetric_difference those in only one.
2 Intersection
let ortak: Vec<i32> = a.____(&b).copied().collect();
let ortak: Vec<i32> = a.intersection(&b).copied().collect();
Explanation: intersection gives the elements common to both sets.
3 Operation and result (a = {1,2,3,4}, b = {3,4,5})
| Term | Meaning |
|---|---|
intersection |
{3, 4} |
union |
{1, 2, 3, 4, 5} |
a.difference(&b) |
{1, 2} |
symmetric_difference |
{1, 2, 5} |