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.
In this example,
map1
containing key-value pairs 1 to 'a'
, 2 to 'b'
, and 3 to 'c'
.minus()
function on map1
with key 2
.2
is removed from map1
.fun main(args: Array<String>) {
val map1 = mapOf(1 to 'a', 2 to 'b', 3 to 'c');
val result = map1.minus(2);
print(result);
}
{1=a, 3=c}
In this example,
map2
containing key-value pairs 'a' to 1
, 'b' to 2
, and 'c' to 3
.minus()
function on map2
with keys 'b'
and 'c'
provided in a list.'b'
and 'c'
are removed from map2
.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);
}
{a=1}
In this example,
map3
containing key-value pairs 1 to "apple"
, 2 to "banana"
, and 3 to "cherry"
.minus()
function on map3
with keys 2
and 3
provided in a sequence.2
and 3
are removed from map3
.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);
}
{1=apple}
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.