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
removeAllmethod 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 valueval 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 mapval entries = map.entries;// remove all entries with even value as keysentries.removeAll{ (key, _) -> key % 2 == 0 }println("\nAfter removing the entries with even keys. \nThe map is : $map")}
Explanation
- Line 3: We create a new
LinkedHashMapobject namedmap. We use thelinkedMapOfmethod to create an emptyLinkedHashMap. - Lines 4 - 7: We add four new entries,
{1=one, 2=two,3=three, 4=four}, to themapusing theput()method. - Line 10: We access the
entriesproperty of themapto get the map’s entries (key-value pair). Theentriesproperties return the map’s keys as aMutableSet. - Line 12: We use the
removeAllmethod on the returnedentriesto 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}.