Sunday, 7 March 2021

Kotlin Collection - Mathematic Sets Specific Operation - Union, Intersection & Subract

The Kotlin collections package contains extension functions for popular operations on sets: finding intersections, merging, or subtracting collections from each other.

To merge two collections into one, use the union() function. It can be used in the infix form a union b. Note that for ordered collections the order of the operands is important: in the resulting collection, the elements of the first operand go before the elements of the second.

To find an intersection between two collections (elements present in both of them), use intersect(). To find collection elements not present in another collection, use subtract(). Both these functions can be called in the infix form as well, for example, a intersect b

Code Snippet:

val universityDefCenters = listOf("Delhi", "Mumbai","Puducherry","Chennai")
val universitySouthCenters = listOf("Karnataka", "Puducherry","Chennai", "Kerala")

val allCenters= universityDefCenters union universitySouthCenters
val commonCenters = universityDefCenters intersect universitySouthCenters
val nonSouthCenters = universityDefCenters subtract universitySouthCenters

println("All Centers (Union): $allCenters")
println("Common Centers (Intersection): $commonCenters")
println("Non-South Centers (Subtract): $nonSouthCenters")

All Centers (Union): [Delhi, Mumbai, Puducherry, Chennai, Karnataka, Kerala]
Common Centers (Intersection): [Puducherry, Chennai]
Non-South Centers (Subtract): [Delhi, Mumbai]

No comments: