![]() |
VOOZH | about |
Kotlin is a statically typed, general-purpose programming language developed by JetBrains. The company famous for creating world-class IDEs like IntelliJ IDEA, PhpStorm, and AppCode. Kotlin was first introduced by JetBrains in 2011 and is designed to run on the Java Virtual Machine (JVM). It is an object-oriented language and is often seen as a “better language” compared to Java because of its concise syntax and safety features. Still, Kotlin is fully interoperable with Java, which means we can use Kotlin and Java code together in the same project without any issues.
In this article, we will learn how to merge two or more collections into one in Kotlin.
In Kotlin, a collection (like a list or a set) can be either mutable or immutable.
Example:
val list = listOf("a", "b", "c") // Immutable list
val mutableList = mutableListOf("a", "b", "c") // Mutable list
In the first case, we cannot add or remove items from list. But with mutableList, we can change its content.
Let's create two lists, listA and listB, as shown below.
Example:
Notice that Kotlin can understand (infer) the type of these lists from the values we put inside them, so we don’t need to specify <String> unless we really want to.
To merge the contents of listA into listB, we can use the addAll() method.
Example:
Output:
[a, c, a, a, b]In this case, all elements from listA are added to listB. Notice that duplicates are not removed, both lists are simply combined.
If we want to merge two lists but keep only unique elements, we can use the union() function.
Example:
Output:
[a, c, b]Here, union() returns a new set containing only unique values from both lists.
The same concept works with sets. Sets automatically store only unique values.
Example:
Output:
[a, b, c, d]With sets, addAll() and union() give the same result, because sets never allow duplicate values.
For maps (key-value pairs), we cannot use addAll() or union(). Instead, we use putAll().
Example:
Output:
{a=2, b=2, d=4}Notice that the key "a" was present in both maps. After merging, the value from mapB replaces the value from mapA, because putAll() overwrites existing keys.
Another easy way to merge two collections is by using the + operator.
Example:
Output:
[a, b, c, d, e, f]The + operator joins both lists and returns a new list. It does not change the original lists.
We can also use the plus() function in the same way.
Example:
Output:
[a, b, c, d, e, f]This method does exactly what the + operator does. It combines two lists into a new one.