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

Set Operations with Set (Union, Intersection, Difference)

In this lesson you will learn how to compute unions, intersections, and differences in Kotlin, covering the basics of set operations. This is for anyone searching for "Kotlin Set operations".

Kotlin's Set provides the infix functions union, intersect, and subtract, computing the union, intersection, and difference directly.

The sample code applies a union b, a intersect b, and a subtract b to the two sets {1, 2, 3, 4} and {3, 4, 5, 6}, sorting each result with .sorted() so it reads clearly.

A common stumbling block for beginners is that these are infix functions - a special form. Beyond the ordinary a.union(b) you can also write a union b, almost like an operator, which is characteristic of Kotlin.

It is a useful way of thinking for real data work, such as finding the users common to two groups, and the ideas behind intersection and difference also carry over to understanding join operations in SQL.

๐Ÿ“– 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)