How to get size of map?
Asked Answered
M

1

5

Is it possible to get map length/size? For some reason, I need to know the size of the map for debugging purposes.

I cant seem to do something like this:

map = new Map<Int, MyObject>();
map.set(.., ..);
map.set(.., ..);
map.length // should be 2

I hope this is possible. If its not, why?

Mackenzie answered 18/10, 2017 at 14:30 Comment(0)
M
8

You can use Lambda.count(map).

But know that this will iterate through all values and might be expensive.


As to why there's no length property in the interface:

Map implementation is rarely length-based so it's hard to know the length unless you maintain an additional counter for it, which in most of the cases is not useful.

Issue #1663: Size of *Map and other Data Structures (comment)

Myrtismyrtle answered 18/10, 2017 at 14:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.