To access items in a Set in Kotlin, you can use various methods such as iterating over the set or using specific methods like contains to check for item existence.
In this example,
fruitSet
with some initial values.fun main() {
val fruitSet = setOf("Apple", "Banana", "Cherry")
for (fruit in fruitSet) {
println(fruit)
}
}
Apple Banana Cherry
In this example,
numberSet
with some initial values.contains
method to check if an item exists in the set.contains
method returns true if the item is in the set, otherwise false.fun main() {
val numberSet = setOf(1, 2, 3, 4, 5)
val containsThree = numberSet.contains(3)
println("Set contains 3: $containsThree")
}
Set contains 3: true
In this example,
fun main() {
val colorSet = setOf("Red", "Green", "Blue")
val colorList = colorSet.toList()
val secondColor = colorList.getOrNull(1)
println("Second color in set: $secondColor")
}
Second color in set: Green
In this tutorial, we learned How to Access Items in a Set in Kotlin language with well detailed examples.