Hash Sets are collections of unique items i.e no element can be repeated.
Hash Sets were designed to give us a way of adding and looking for unique values in a collection in a quick manner.
The values in a Hash Set can be either simple primitives like strings or integers as well as more complex object types like lists or arrays.
In Kotlin, a Hash Set is a HashSet object, created with hashSetOf() or toHashSet().
Creation:
To create a new empty HashSet that holds Strings, you use the following syntax:
val mySet = hashSetOf<String>()
Creating an empty Set takes O(1) time.
Constructing from a collection
You can also build a set from an existing collection or array with toHashSet(). All the unique elements of the collection will be added to the new set:
val elements = listOf("b", "c", "c", "d")
val mySet = elements.toHashSet()
// mySet contains {"b", "c", "d"}
This takes O(n) time, where n is the number of elements in the collection.
Adding elements:
To add an element to the set, you use the add() method:
val elements = listOf("b", "c", "c", "d")
val mySet = elements.toHashSet()
// Adding new elements
mySet.add("x")
// Adding an existing element
mySet.add("d") // nothing happens
// mySet contains {"b", "c", "d", "x"}
The Set first checks if that element already exists and if so, it does nothing and also doesn't raise an error.
Adding an element to a Set takes O(1) time.
Checking if a value exists:
To check if a Set has a specific element, you use the contains() method which returns true if the set contains the element, otherwise, it returns false.
val elements = listOf("b", "c", "c", "d")
val mySet = elements.toHashSet()
var exists = mySet.contains("c") // exists is true
exists = mySet.contains("x") // exists becomes false
Checking if a value exists in a Set takes O(1) time.
Removing elements:
To delete a specified element from a set, you use the remove() method:
val elements = listOf("b", "c", "c", "d")
val mySet = elements.toHashSet()
// Deleting elements
mySet.remove("c")
// Deleting a non-existent element
mySet.remove("z") // does nothing
// mySet contains {"b", "d"}
The Set first checks if that key exists and if not, it does nothing and also doesn't raise an error, so it's safe to delete non-existing elements.
Removing an element from a Set takes O(1) time.
Iterating over the Set values:
If we want to iterate over values of the Set, we can use the for loop along with the in keyword:
val elements = listOf("b", "c", "c", "d")
val mySet = elements.toHashSet()
for (value in mySet) {
println(value)
}
// This will print the following:
// b
// c
// d
// (a HashSet doesn't promise any particular order)
Iterating over a Set takes O(n) time.
Space Complexity
A Set uses O(n) space, where n is the number of elements existing in the Set.
Assignment
Follow the Coding Tutorial and let's play with some Hash Sets.
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. PRO is unlimited.
