nww04
nww04

Reputation: 1857

How to get size of map?

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?

Upvotes: 5

Views: 3991

Answers (1)

Jonas Malaco
Jonas Malaco

Reputation: 1557

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)

Upvotes: 8

Related Questions