Remove LinkedHashMap entries that match test conditions in Kotlin

To remove the entries of LinkedHashMap that match a specific condition we:

  • Get the entries of the LinkedHashMap.
  • Use the removeAll method to remove all the entries that match a specific condition.
fun main() {
//create a new LinkedHashMap which can have integer type as key, and string type as value
val map: LinkedHashMap<Int, String> = linkedMapOf()
map.put(1, "one")
map.put(2, "two")
map.put(3, "three")
map.put(4, "four")
println("The map is : $map")
// get all entries of the map
val entries = map.entries;
// remove all entries with even value as keys
entries.removeAll{ (key, _) -> key % 2 == 0 }
println("\nAfter removing the entries with even keys. \nThe map is : $map")
}

Explanation

  • Line 3: We create a new LinkedHashMap object named map. We use the linkedMapOf method to create an empty LinkedHashMap.
  • Lines 4 - 7: We add four new entries, {1=one, 2=two,3=three, 4=four}, to the map using the put() method.
  • Line 10: We access the entries property of the map to get the map’s entries (key-value pair). The entries properties return the map’s keys as a MutableSet.
  • Line 12: We use the removeAll method on the returned entries to remove all the entries with an even value as a key. In our case, the mapping for key 2,4 is removed. After calling this method, the map is {1=one,3=three}.

Free Resources