Kotlin Map minus()
Syntax & Examples


Syntax of Map.minus()

There are 4 variations for the syntax of Map.minus() extension function. They are:

1.
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.

2.
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.

3.
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.

4.
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 map1 containing key-value pairs 1 to 'a', 2 to 'b', and 3 to 'c'.
  • We then apply the minus() function on map1 with key 2.
  • As a result, the entry with key 2 is removed from map1.
  • 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 map2 containing key-value pairs 'a' to 1, 'b' to 2, and 'c' to 3.
  • We then apply the minus() function on map2 with keys 'b' and 'c' provided in a list.
  • As a result, the entries with keys 'b' and 'c' are removed from map2.
  • 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 map3 containing key-value pairs 1 to "apple", 2 to "banana", and 3 to "cherry".
  • We then apply the minus() function on map3 with keys 2 and 3 provided in a sequence.
  • As a result, the entries with keys 2 and 3 are removed from map3.
  • 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.