Sets, pairs and destructuring
Sets, pairs and destructuring
A club membership list should avoid duplicate entries, while a small result can carry a total and count together. Set represents unique elements. Pair and Triple package a fixed number of values, and destructuring gives their components local names.
What you’ll learn
- Choose unique membership versus ordered repetition.
- Destructure a fixed pair.
Sets, pairs and destructuring in the example
Unique membership
A club membership list should avoid duplicate entries, while a small result can carry a total and count together.
Unique membershipShared member
Set intersection finds shared members, union combines membership and subtraction removes members.
Shared memberDestructure result
Duplicate Diya contributes only one set member.
Destructure result
Understand sets, pairs and destructuring
Set intersection finds shared members, union combines membership and subtraction removes members. Do not rely on every set implementation having one display order. Destructuring follows component functions; a Pair’s first and second positions are not domain-specific names by themselves.
Follow sets, pairs and destructuring
Save the complete source as Main.kt and use the Kotlin/JVM environment. No separate input file is needed.
Kotlin/JVM · complete program
fun main() {
val art = setOf("Diya", "Saira", "Diya")
val music = setOf("Saira", "Noor")
println((art intersect music).sorted())
val (total, count) = 160 to 2
println(total / count)
}Expected output
[Saira]
80Follow the execution
Duplicate Diya contributes only one set member. The sorted intersection contains Saira. The infix to function forms a Pair, whose two components become total and count. Their integer division is 80.
Try this in the Kotlin compiler by pasting the complete program.
Practice: Sets, pairs and destructuring
Your task: Which collection should preserve repeated attendance entries in their original order?
Kotlin/JVM · complete program
fun main() {
val art = setOf("Diya", "Saira", "Diya")
val music = setOf("Saira", "Noor")
println((art intersect music).sorted())
val (total, count) = 160 to 2
println(total / count)
}Worked answer
A list should. A set removes duplicates and does not offer a universal original-order guarantee.
Sets, pairs and destructuring: the important boundary
For a meaningful long-lived report model, a named data class can be clearer than a Pair. Set uniqueness follows equality and hashing rules, not proof that equal display names belong to one person.
Check your understanding
Sets, pairs and destructuring: what to keep in mind
A list should. A set removes duplicates and does not offer a universal original-order guarantee. For a meaningful long-lived report model, a named data class can be clearer than a Pair.
Further reading: official Kotlin documentation for this topic.
Reaching the recap and completing the quizzes are separate milestones.