简体   繁体   中英

get the size of arrayList inside Hashmap

I have an ArrayList inside a HashMap . Using minimum line of code , I need to get the size of 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 .

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(); or map.size(); and here for more infos

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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