Merge two sets in Kotlin
This article explores different ways to merge two sets in Kotlin. Assume that the elements of both sets are mutually exclusive; otherwise, duplicates would be silently discarded during the merge process.
1. Using plus operator
The standard solution to join two sets in Kotlin is with the + operator or the plus() function. To illustrate, consider the following example, which creates a new set that is a join of both sets.
|
1 2 3 4 5 6 7 8 9 10 11 |
fun <T> mergeSets(first: Set<T>, second: Set<T>): Set<T> { return first + second // or, use `first.plus(second)` } fun main() { var first: MutableSet<Int> = (1..2).toMutableSet() var second: MutableSet<Int> = (3..5).toMutableSet() var set: Set<Int> = mergeSets(first, second) println(set) } |
2. Using addAll() function
Alternatively, you can call the addAll() function provided by the Set Interface to add all the specified collection elements to the result set.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun <T> mergeSets(first: Set<T>, second: Set<T>): Set<T> { val result: MutableSet<T> = HashSet() result.addAll(first) result.addAll(second) return result } fun main() { var first: MutableSet<Int> = (1..2).toMutableSet() var second: MutableSet<Int> = (3..5).toMutableSet() var set: Set<Int> = mergeSets(first, second) println(set) } |
3. Using setOf() function
Another plausible way is to pass the expanded collection returned by the Spread operator * to the mutableSetOf() or setOf() function.
|
1 2 3 4 5 6 7 8 9 10 11 |
inline fun <reified T> mergeSets(first: Set<T>, second: Set<T>): Set<T> { return setOf(*first.toTypedArray(), *second.toTypedArray()) } fun main() { var first: MutableSet<Int> = (1..2).toMutableSet() var second: MutableSet<Int> = (3..5).toMutableSet() var set: Set<Int> = mergeSets(first, second) println(set) } |
4. Using Double Brace Initialization
You can also use Double Brace Initialization, which internally creates an anonymous inner class with an instance initializer in it. This approach should be best avoided.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
fun <T> mergeSets(first: Set<T>, second: Set<T>): Set<T> { return object : HashSet<T>() { init { addAll(first) addAll(second) } } } fun main() { var first: MutableSet<Int> = (1..2).toMutableSet() var second: MutableSet<Int> = (3..5).toMutableSet() var set: Set<Int> = mergeSets(first, second) println(set) } |
That’s all about merging two sets in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)