简体   繁体   English

获取Hashmap中arrayList的大小

[英]get the size of arrayList inside Hashmap

I have an ArrayList inside a HashMap .我在 HashMap 中有一个 ArrayList 。 Using minimum line of code , I need to get the size of ArrayList .使用最少的代码行,我需要获取 ArrayList 的大小。

 Map<String, ArrayList<Map<String,String>>> map = new HashMap<String, ArrayList<Map<String,String>>>();
             map.put("data",childList);

How to get the size of the "childlist" from the variable "map" using one line of code .如何使用一行代码从变量“map”中获取“childlist”的大小。

Get a map value by key.通过键获取地图值。 Then check if it is not null.然后检查它是否不为空。 And then if the map is not generic, this is how in your case, then the value is an instance of list.然后,如果地图不是通用的,这就是您的情况,那么该值是列表的一个实例。 So you get its size directly.所以你可以直接得到它的大小。

 Map<String, ArrayList<Map<String,String>>> map = new HashMap<String, ArrayList<Map<String,String>>>();
 map.put("data",childList);

 List<Map<String,String>> data = map.get("data");
 int size = 0;
 if (data != null) {
     size = data.size();
 }

Oddly enough, when I tried recreating your example and this seemed to work just fine.奇怪的是,当我尝试重新创建您的示例时,这似乎工作得很好。

map.get("data").size();

That being said, I ran into this problem recently and my solution ended up involving casting types to look something like话虽如此,我最近遇到了这个问题,我的解决方案最终涉及到类型转换,看起来像

((ArrayList<Map<String,String>>) map.get("data")).size();

Which comes down to surrounding your map call and its casting call with parenthesis, and then work with the list normally from there.这归结为用括号包围您的地图调用及其转换调用,然后从那里正常使用列表。

        ArrayList<Map<String, String>> childList = new ArrayList<Map<String, String>>();
        Map<String, ArrayList<Map<String,String>>> map = new HashMap<String, ArrayList<Map<String,String>>>();
        map.put("data", childList);
        int size = map.get("data").size();

try: map.length();尝试: map.length(); or map.size();map.size(); and here for more infos在这里了解更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM