In Kotlin, working with collections like lists, sets, and maps is made easier and more readable thanks to operators like + (plus) and – (minus). These operators help you combine or remove elements from collections in a very natural way, just like doing math, but with objects instead of numbers.
Working With Lists
The + (Plus) Operator
The + operator is used when you want to add elements to a collection. It doesn’t change the original collection. Instead, it returns a new read-only collection that contains all the elements from the first collection plus the elements from the second collection. You can add a single item or an entire collection using +.
Syntax:
val result = list1 + list2Example:
fun main() {
val list1 = listOf("three", "one")
val list2 = listOf("twenty", "zero")
val result = list1 + list2
println(result)
}
Output:
[three, one, twenty, zero]The - (Minus) Operator
The – operator is used when you want to remove elements from a collection. Like +, it doesn't modify the original collection, it returns a new one with elements removed. You can remove a single element, a group of elements, and even another collection
Example:
fun main() {
val list = listOf("three", "one", "twenty", "zero")
val result = list - listOf("three", "zero")
println(result)
}
Output:
[one, twenty]Working with Maps
The + (Plus) Operator
These operators behave slightly differently when you use them with maps. You can add a single key-value Pair and an another map. The result is a new map that combines all the entries from both. If the same key appears in both maps, the value from the right-hand side will replace the one on the left.
Example:
fun main() {
val map1 = mapOf("one" to 1, "two" to 2)
val map2 = mapOf("three" to 3, "four" to 4)
val result = map1 + map2
println(result)
}
Output:
{one=1, two=2, three=3, four=4}The - (Minus) Operator
When you use – with maps, it removes entries by their keys. You can remove one key or a group of keys.
Example:
fun main() {
val map = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
val result = map - listOf("one", "four")
println(result)
}
Output:
{two=2, three=3}Note: Both + and – always return a new collection. They do not change the original collection. If you want to modify a mutable collection, you’ll need to use functions like add() or remove() directly on that collection.