Start learning free

LESSON 234 OF 677 · SETS

Sets in Kotlin

Lesson

TL ; DR:

A HashSet holds values without repeats. Adding a value that is already in it changes nothing.


val pets = hashSetOf<String>()    // an empty set
pets.add("cat")
pets.add("dog")
pets.add("cat")                   // already in it, no change

println(pets.size)                // 2
println(pets.contains("dog"))     // true


Full lesson:

A list keeps every value you put in it, repeats too. Sometimes you only need to know which values there are. A set is made for that.

A set holds each value once. Adding a value that is already in it changes nothing.

  • hashSetOf<String>() makes an empty set of strings.
  • s.add(x) puts x in the set s.
  • s.contains(x) is true when x is in the set.
  • s.size gives how many values the set holds.
  • list.toHashSet() builds a set from a list. Its repeats go in once.

Checking s.contains(x) is fast, even for a big set. A list's contains looks at the values one by one.

Watch out for setOf(...). It makes a read-only set, so add doesn't compile on it. Use hashSetOf for a set you change.

A HashSet has no order and no indexes. A printed set may show its values in any order.


Your task

The camp's sign-up list, names, has some names twice. Build a HashSet named kids from it.

Then Zoe signs up, and Ava signs up again. Add both names to kids.

Last, if kids contains "Leo", print Leo is coming.

The code already prints the number of kids twice.

Expected output:

3 kids
4 kids
Leo is coming
STEP 1 OF 3
    Ctrl + Enter to check