Sets

Learn to create sets, add and remove elements, handle duplicates, and work with mutable sets.

Introduction

We use sets instead of lists when:

  • We want to ensure that elements in our collection are unique (sets keep only unique elements).

  • We frequently look for an element in a collection (finding elements in a set is much more efficient than doing so in a list.

Note: The default set is based on a hash table algorithm, which makes finding an element with a properly implemented hashCode really fast. This operation time does not depend on the number of elements in the set (so it has O(1)O(1)complexity).

Sets are quite similar to lists, which is why similar methods are used to operate on them. However, sets do not treat order as seriously as lists, and some kinds of sets do not respect order at all. This is why we cannot get elements by index.

Creating sets

We create a set using the setOf function; then we specify its values using arguments.

Get hands-on with 1200+ tech skills courses.