The count
method gets the number of entries in LinkedHashMap
.
The count method has two variations:
// 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
The count
method optionally takes the
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") }
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 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.
RELATED TAGS
CONTRIBUTOR
View all Courses