Instruction 2

Set

A set stores only unique values. Remember that a List will happily store duplicates? In the Set, every duplicate is removed by the Set object. For this reason, the order of elements isn’t defined, as some items may be removed if duplicated. The Set interface represents sets in Kotlin.

Read-only Sets

A Set may also be mutable or immutable, like a List. To initialize an immutable set, use setOf:

fun main() {
  val oceans = setOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean", "Atlantic Ocean", "Indian Ocean")
  println(oceans)
}

Run the above code. println(oceans) contains the following output:

[Pacific Ocean, Southern Ocean, Arctic Ocean, Atlantic Ocean, Indian Ocean]

Note: The contents of a Set are displayed in square braces, [], like the List.

Mutable Sets

Here’s an example of the mutableSetOf method, which initializes a mutable Set:

fun main() {
  val oceans = mutableSetOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean", "Atlantic Ocean", "Indian Ocean")
  println(oceans)
}

Use emptySet to create an emptySet:

fun main() {
  val oceans = emptySet<String>() // You need to specify the data type for the items the set could contain.
  println(oceans)
}

To add items to a mutable set, call the add method on the object to add a single item or addAll to add all items from another collection:

fun main() {
  val oceans = mutableSetOf("Atlantic Ocean", "Indian Ocean")
  println(oceans)
  oceans.add("Pacific Ocean")
  println(oceans)
  oceans.addAll(listOf("Southern Ocean", "Arctic Ocean"))
  println(oceans)
}

Run the above code. println(oceans) contains the following outputs:

[Atlantic Ocean, Indian Ocean]
[Atlantic Ocean, Indian Ocean, Pacific Ocean]
[Atlantic Ocean, Indian Ocean, Pacific Ocean, Southern Ocean, Arctic Ocean]

To reference an element by its index, use the element’s 0-based index with the elementAt() method:

fun main() {
  val oceans = mutableSetOf("Atlantic Ocean", "Indian Ocean")
  println(oceans.elementAt(0))
}

Run the above code. The output contains the following:

Atlantic Ocean

To remove an element referencing the value of the element, use the remove() method:

fun main() {
  val oceans = mutableSetOf("Atlantic Ocean", "Indian Ocean")
  oceans.remove("Atlantic Ocean")
  println(oceans)
}

Run the above code. The output contains the following:

[Indian Ocean]

A Set can be iterated like a List.

fun main() {
  val oceans = mutableSetOf("Atlantic Ocean", "Indian Ocean")
  for (ocean in oceans) {
    println(ocean)
  }
}

Run the above code. The output contains the following:

Atlantic Ocean
Indian Ocean

Map

A Map differs from the List and Set in that they store key-value pairs instead of single items. A key in a Map is unique. If a new key duplicates an existing key, the existing key value is updated with the new value.

A map can also be empty. To initialize an empty map, use the emptyMap built-in function. You need to specify the type for both the key and value. This is the same initialization you wrote for List and Set:

fun main() {
  val oceans = emptyMap<Int, String>()
  println(oceans)
}

Run the above code. The output contains the following:

{}

Note: The contents of a Map are displayed in curly braces, {}.

A map may be defined as immutable by assigning the Map to a val. To assign a value to a key, separate the key from the value using the keyword to:

fun main() {
  val oceans = mapOf(0 to "Atlantic Ocean", 1 to "Indian Ocean")
  println(oceans)
}

Run the above code. The output contains the following:

{0=Atlantic Ocean, 1=Indian Ocean}

To test an immutable Map, attempt to call the put() method:

fun main() {
  val oceans = mapOf(0 to "Atlantic Ocean", 1 to "Indian Ocean")
  println(oceans)
  oceans.put(2, "Pacific Ocean")
  println(oceans)
}

Run the above code. The output contains the following error:

Unresolved reference: put

A Map may also be mutable:

fun main() {
  val oceans = mutableMapOf(0 to "Atlantic Ocean", 1 to "Indian Ocean")
  println(oceans)
  oceans.put(2, "Pacific Ocean")
  println(oceans)
}

Run the above code. The output contains the following:

{0=Atlantic Ocean, 1=Indian Ocean}
{0=Atlantic Ocean, 1=Indian Ocean, 2=Pacific Ocean}

When you loop over a map, remember that each item is a key-value pair. Use the iterator() function from the entries property of the map to iterate over a map:

fun main() {
  val oceans = mutableMapOf(0 to "Atlantic Ocean", 1 to "Indian Ocean")
  for (ocean in oceans.entries.iterator()) {
      println("${ocean.key} : ${ocean.value}")
  }
}

Run the above code. The output contains the following:

0 : Atlantic Ocean
1 : Indian Ocean

Note: You can also iterate over the keys only or the values only.

Collection Elements

The items in a collection are usually of the same type or subtype, but they may also be completely different types.

Below is a list of objects of different data types:

fun main() {
  val mixedTypesList = listOf("Doughnuts", 200.0f, true, mapOf("color" to "Red"))
  println(mixedTypesList)
}

Run the above code. The output contains the following:

[Doughnuts, 200.0, true, {color=Red}]
See forum comments
Download course materials from Github
Previous: Instruction 1 Next: Instruction 3