Kotlin Map minus()
Syntax & Examples
Syntax of Map.minus()
There are 4 variations for the syntax of Map.minus() extension function. They are:
operator fun <K, V> Map<out K, V>.minus(key: K): Map<K, V>This extension function returns a map containing all entries of the original map except the entry with the given key.
operator fun <K, V> Map<out K, V>.minus( keys: Iterable<K> ): Map<K, V>This extension function returns a map containing all entries of the original map except those entries the keys of which are contained in the given keys collection.
operator fun <K, V> Map<out K, V>.minus( keys: Array<out K> ): Map<K, V>This extension function returns a map containing all entries of the original map except those entries the keys of which are contained in the given keys array.
operator fun <K, V> Map<out K, V>.minus( keys: Sequence<K> ): Map<K, V>This extension function returns a map containing all entries of the original map except those entries the keys of which are contained in the given keys sequence.
✐ Examples
1 Remove entry with key 2 from map
In this example,
- We create a map named
map1containing key-value pairs1 to 'a',2 to 'b', and3 to 'c'. - We then apply the
minus()function onmap1with key2. - As a result, the entry with key
2is removed frommap1. - We print the result to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map1 = mapOf(1 to 'a', 2 to 'b', 3 to 'c');
val result = map1.minus(2);
print(result);
}Output
{1=a, 3=c}2 Remove entries with keys 'b' and 'c' from map
In this example,
- We create a map named
map2containing key-value pairs'a' to 1,'b' to 2, and'c' to 3. - We then apply the
minus()function onmap2with keys'b'and'c'provided in a list. - As a result, the entries with keys
'b'and'c'are removed frommap2. - We print the result to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map2 = mapOf('a' to 1, 'b' to 2, 'c' to 3);
val result = map2.minus(listOf('b', 'c'));
print(result);
}Output
{a=1}3 Remove entries with keys 2 and 3 from map
In this example,
- We create a map named
map3containing key-value pairs1 to "apple",2 to "banana", and3 to "cherry". - We then apply the
minus()function onmap3with keys2and3provided in a sequence. - As a result, the entries with keys
2and3are removed frommap3. - We print the result to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map3 = mapOf(1 to "apple", 2 to "banana", 3 to "cherry");
val result = map3.minus(sequenceOf(2, 3));
print(result);
}Output
{1=apple}Summary
In this Kotlin tutorial, we learned about minus() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.