如何获取地图的大小?

How to get size of map?

是否可以获取地图length/size?出于某种原因,出于调试目的,我需要知道地图的大小。

我似乎不能做这样的事情:

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

我希望这是可能的。如果不是,为什么?

您可以使用 Lambda.count(map).

但请注意,这将遍历所有值并且可能开销很大。


关于界面为什么没有length属性:

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)