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:

  1. It can get the number of entries in the map.
  2. It can also get the number of entries that match a specific test condition.

Syntax

// number of entries in the map
fun <K, V> Map<out K, V>.count(): Int
//number of entries which match a specific conditoin
fun <K, V> Map<out K, V>.count(
predicate: (Entry<K, V>) -> Boolean
): Int
Syntax of count method

The count method optionally takes the predicate functionPredicate is a Functional interface that takes one argument and returns either true or false based on the condition defined. as an argument.

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 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")
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 LinkedHashMap object named map. We use the linkedMapOf method to create an empty LinkedHashMap.

  • Lines 4-7: We add four new entries to the map using the put() method.

  • Line 9: We use the count method to get the number of entries present in the map. In our case, there are four entries. Hence, 4 is returned.

  • Line 11: We use the count method with a predicate function as an argument. The predicate functionPredicate is a Functional interface, which takes one argument and returns either true or false based on the condition defined. returns true if the key is an odd number. In our case, there are two entries with odd keys. Hence, 2 is returned as a result.

Free Resources