How to check the number of entries in LinkedHashMap in Kotlin
The count method gets the number of entries in LinkedHashMap.
The count method has two variations:
- It can get the number of entries in the map.
- It can also get the number of entries that match a specific test condition.
Syntax
// number of entries in the mapfun <K, V> Map<out K, V>.count(): Int//number of entries which match a specific conditoinfun <K, V> Map<out K, V>.count(predicate: (Entry<K, V>) -> Boolean): Int
The count method optionally takes the
Code
The code below demonstrates how to get the number of entries present in the map:
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")println("The number of entries in the map is : ${map.count()}")val oddEntries = map.count{ (k, _) -> k %2 ==0 }println("The number of entries in the map with odd key is : $oddEntries")}
Explanation
-
Line 3: We created a new
LinkedHashMapobject namedmap. We use thelinkedMapOfmethod to create an emptyLinkedHashMap. -
Lines 4-7: We add four new entries to the
mapusing theput()method. -
Line 9: We use the
countmethod to get the number of entries present in themap. In our case, there are four entries. Hence,4is returned. -
Line 11: We use the
countmethod with a predicate function as an argument. The returnspredicate function Predicate is a Functional interface, which takes one argument and returns either true or false based on the condition defined. trueif the key is an odd number. In our case, there are two entries with odd keys. Hence,2is returned as a result.