The minus
method creates a new Map
from the current LinkedHash, then removes the entries with the passed keys and returns the created Map
as a result.
//single key
operator fun <K, V> Map<out K, V>.minus(key: K): Map<K, V>
// iterable keys as argument(eg.list)
operator fun <K, V> Map<out K, V>.minus(
keys: Iterable<K>
): Map<K, V>
// keys array as argument
operator fun <K, V> Map<out K, V>.minus(
keys: Array<out K>
): Map<K, V>
// keys sequence as an argument
operator fun <K, V> Map<out K, V>.minus(
keys: Sequence<K>
): Map<K, V>
This method can take any one of the below values as an argument:
This method returns a Map
as a value.
The code below demonstrates how to use the minus
method:
fun main() {//create a new LinkedHashMap which can have integer type as key, and string type as valueval map: LinkedHashMap<Int, String> = linkedMapOf()// add two entriesmap.put(1, "one")map.put(2, "two")map.put(3, "three")println("\nThe map is : $map")var newMap = map.minus(1);println("map.minus(1) : ${newMap}")//iterableval list = listOf(1,2);newMap = map.minus(list);println("\nmap.minus(list) : ${newMap}")//arrayval array = arrayOf(1,3);newMap = map.minus(array);println("\nmap.minus(array) : ${newMap}")}
In the above code:
Line 3: We create a new LinkedHashMap
object with map
. We use the linkedMapOf
method to create an empty LinkedHashMap
.
Lines 6 to 8: We add three entries to the map {1=one,2=two,3=three}
using the put
method.
Line 11: We use the minus
method with 1
as an argument. This returns a new map created from the map
object. The entry with key 1 is removed and returns the created map. The returned map is {2=two, 3=three}
.
Line 15: We create a list with elements 1
and 2
using the listOf
method.
Line 16: We use the minus
method with list
as an argument. This returns a new map created from the map
object. In the created map, all the entries with the keys that match the list’s elements are removed. The returned map is {3=three}
.
Line 20: We create an array with elements 1
and 3
using the arrayOf
method.
Line 16: We use the minus
method with array
as an argument. This returns a new map created from the map
object. In the created map, all the entries with the keys that match the array’s elements are removed. The returned map is {2=two}
.