Learn
Sets
Accessing Elements in a Set

Unlike lists, a set is an un-ordered collection, thus we can’t use square brackets and indices to retrieve its elements. However, a set is an intelligent tool that stores its elements in the order in which each element was inserted. We can utilize this order along with a function, elementAt(), to access and retrieve elements.

The elementAt() function accepts an Integer value and returns the element at that position. This function is useful for collections that do not possess index access.

listName.elementAt(integer) 

Assume we’re writing a program that keeps track of animals that are no longer on the endangered list:

var nonEndangered = setOf("Louisiana Black Bear", "Northern Brown Kiwi", "Gray Wolf", "Arabian Oryx")

To retrieve the animal, "Gray Wolf" , we’d use the following syntax:

nonEndangered.elementAt(2) // Gray Wolf

Since Kotlin is a null safe language, it encourages developers to avoid NullPointerException errors wherever they can by using safer variations of function.

In the case that an element does not exist at a specified position, our code would throw an error:

nonEndangered.elementAt(5) // Exception error

Exception error:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Collection doesn't contain element at index 5.

To avoid this, we can use the elementAtOrNull() function, a safer variation of elementAt() to return null as opposed to an error when an element does not exist in the set:

nonEndangered.elementAtOrNull(5) // null

Instructions

1.

In Islands.kt, declare a variable, islandsOfHawaii, and assign it an immutable set containing the following elements:

  • "Maui"
  • "Lanai"
  • "Oahu"
  • "Kauai"
2.

On the following line, retrieve the island of Oahu from the set using the elementAt() function and its position.

Wrap this code in a print statement to see the output.

3.

Use the elementAtOrNull() function to retrieve an element from the 6th position.

Wrap this code in a print statement to see the output. You should not see an error in the terminal.

Folder Icon

Take this course for free

Already have an account?