To create a Set of Sets in Kotlin, you can use the setOf()
function to create individual sets and then nest them within another set using the same function.
In this example,
set1
, set2
, and set3
using the setOf()
function. set1
contains the elements 1, 2, 3
, set2
contains the elements 4, 5, 6
, and set3
contains the elements 7, 8, 9
.setOfSets
using the setOf()
function, passing set1
, set2
, and set3
as arguments. This will nest the three sets within a single set.setOfSets
. Within the loop, we print each individual set to standard output.fun main() {
val set1 = setOf(1, 2, 3)
val set2 = setOf(4, 5, 6)
val set3 = setOf(7, 8, 9)
val setOfSets = setOf(set1, set2, set3)
for (set in setOfSets) {
println(set)
}
}
Output: [1, 2, 3] [4, 5, 6] [7, 8, 9]
In this example,
setA
, setB
, and setC
using the setOf()
function. setA
contains the elements "apple", "banana", "cherry"
, setB
contains the elements "dog", "elephant", "fox"
, and setC
contains the elements "grape", "honeydew", "kiwi"
.setOfStringSets
using the setOf()
function, passing setA
, setB
, and setC
as arguments. This will nest the three sets within a single set.setOfStringSets
. Within the loop, we print each individual set to standard output.fun main() {
val setA = setOf("apple", "banana", "cherry")
val setB = setOf("dog", "elephant", "fox")
val setC = setOf("grape", "honeydew", "kiwi")
val setOfStringSets = setOf(setA, setB, setC)
for (set in setOfStringSets) {
println(set)
}
}
Output: [apple, banana, cherry] [dog, elephant, fox] [grape, honeydew, kiwi]
In this tutorial, we learned How to create a Set of Sets in Kotlin language with well detailed examples.