Kotlin Map plus()
Syntax & Examples
Syntax of Map.plus()
There are 5 variations for the syntax of Map.plus() extension function. They are:
operator fun <K, V> Map<out K, V>.plus( pair: Pair<K, V> ): Map<K, V>This extension function creates a new read-only map by replacing or adding an entry to this map from a given key-value pair.
operator fun <K, V> Map<out K, V>.plus( pairs: Iterable<Pair<K, V>> ): Map<K, V>This extension function creates a new read-only map by replacing or adding entries to this map from a given collection of key-value pairs.
operator fun <K, V> Map<out K, V>.plus( pairs: Array<out Pair<K, V>> ): Map<K, V>This extension function creates a new read-only map by replacing or adding entries to this map from a given array of key-value pairs.
operator fun <K, V> Map<out K, V>.plus( pairs: Sequence<Pair<K, V>> ): Map<K, V>This extension function creates a new read-only map by replacing or adding entries to this map from a given sequence of key-value pairs.
operator fun <K, V> Map<out K, V>.plus( map: Map<out K, V> ): Map<K, V>This extension function creates a new read-only map by replacing or adding entries to this map from another map.
✐ Examples
1 Add a single entry to the map
In this example,
- We create a map named
map1containing key-value pairs1 to 'a'and2 to 'b'. - We create a new key-value pair
3 to 'c'. - We use the
plus()operator to add the new pair tomap1. - The resulting map contains the added entry.
- We print the result to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map1 = mapOf(1 to 'a', 2 to 'b');
val pair = 3 to 'c';
val result = map1.plus(pair);
print(result);
}Output
{1=a, 2=b, 3=c}2 Add multiple entries to the map
In this example,
- We create a map named
map2containing key-value pairs'a' to 1and'b' to 2. - We create a list of key-value pairs
('c' to 3)and('d' to 4). - We use the
plus()operator to add the list of pairs tomap2. - The resulting map contains the added entries.
- We print the result to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map2 = mapOf('a' to 1, 'b' to 2);
val pairs = listOf('c' to 3, 'd' to 4);
val result = map2.plus(pairs);
print(result);
}Output
{a=1, b=2, c=3, d=4}3 Add entries from an array to the map
In this example,
- We create a map named
map3containing key-value pairs1 to "apple"and2 to "banana". - We create an array of key-value pairs
(3 to "cherry")and(4 to "date"). - We use the
plus()operator to add the array of pairs tomap3. - The resulting map contains the added entries.
- We print the result to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map3 = mapOf(1 to "apple", 2 to "banana");
val array = arrayOf(3 to "cherry", 4 to "date");
val result = map3.plus(array);
print(result);
}Output
{1=apple, 2=banana, 3=cherry, 4=date}Summary
In this Kotlin tutorial, we learned about plus() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.