Ad space (banner)
๐ŸŽฏKotlin Lessons
Lesson 27 / 68

Working with Set

In this lesson you will learn how to hold duplicate-free data with Set in Kotlin, and understand the basics of the set data structure. This is for anyone searching for "Kotlin Set how to use".

Set is a box that refuses to hold the same value twice. It is handy for stripping duplicates out of an array, or for checking membership quickly.

The sample code builds a set from the duplicate-containing list [1, 2, 2, 3, 3, 3] with .toSet(); the duplicates disappear automatically and only 1, 2, and 3 remain. Notice how contains() checks whether a value is present.

A common stumbling block for beginners is that the order of a Set is not guaranteed. Unlike a list, items are not necessarily kept in insertion order, so a list is a better fit when order matters.

In real-world development, Set's contains() also outperforms a list's once there is a lot of data, making it very handy for removing duplicates.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Kotlin directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)