Sets

A Set is a collection that allows only one element of each value, and automatically prevents duplicates.

The most common Set activity is to test for membership using in or contains():

// Sets/Sets.kt import atomictest.eq fun main(args: Array<String>) { val set = setOf(1, 1, 2, 3, 9, 9, 4) // No duplicates: set eq setOf(1, 2, 3, 4, 9) // Element order is unimportant: setOf(1, 2) eq setOf(2, 1) // Set membership: (9 in set) eq true (99 in set) eq false set.contains(9) eq true set.contains(99) eq false // Does this set contain another set? set.containsAll(setOf(1, 9, 2)) eq true // Set union: set.union(setOf(3, 4, 5, 6)) eq setOf(1, 2, 3, 4, 5, 6, 9) // Set intersection: set intersect setOf(0, 1, 2, 7, 8) eq setOf(1, 2) // Set difference: set subtract setOf(0, 1, 9, 10) eq setOf(2, 3, 4) set - setOf(0, 1, 9, 10) eq setOf(2, 3, 4) }

This example shows:

  1. Placing duplicate items into a Set automatically removes those duplicates.

  2. Element order is not important for sets: two sets are equal if they contain the same elements.

  3. Both in and contains() test for membership.

  4. You can perform the usual Venn-diagram operations like checking for subset, union, intersection and difference, using either dot notation (like set.union(other)) or infix notation (like set intersect other). All the functions union, intersect and subtract are declared as infix.

  5. Set difference can be expressed with either subtract() or the minus operator (-).

To remove duplicates from a List, convert it to a Set:

// Sets/RemoveDuplicates.kt import atomictest.eq fun main(args: Array<String>) { val list = listOf(3, 3, 2, 1, 2) list.toSet() eq setOf(1, 2, 3) list.distinct() eq listOf(3, 2, 1) "abbcc".toSet() eq setOf('a', 'b', 'c') }

Alternatively, you can use distinct(), which returns a List. You may call toSet() on a String to convert it into a set of characters.

As with List, Kotlin provides two creation functions for Set. setOf() is read-only. To create a mutable Set, use mutableSetOf():

// Sets/MutableSet.kt import atomictest.eq fun main(args: Array<String>) { val set = mutableSetOf<Int>() set += 42 set += 42 set eq setOf(42) set -= 42 set eq setOf<Int>() }
The operators += and -= add and remove elements to Sets, just as with Lists.

Previous          Next

©2018 Mindview LLC. All Rights Reserved.