How to extract the size of the list in a map if the keys of the map is known?

StackOverflow https://stackoverflow.com/questions/21939328

  •  14-10-2022
  •  | 
  •  

質問

If below is my map -

Map<String, List<String>> testMap = getInformation(requestParams);

And if I know the keys in the map, then is there any direct way of extracting the size of the list for that key in the map? Or I need to iterate the map and then find out the size of the list corresponding to that key in the map.

UPDATE:-

hello = 1,2,3,4
world = 8,9,10,11,12

If hello is my key, then I would like to extract size which will be 4 for hello key?

Same with if world is the key, then I would like to extract size which will be 5 for world key.

役に立ちましたか?

解決

You first get the element in the map by key and then take the length.

testMap.get(key).size()

他のヒント

If you know the key, you can go directly to the map entry you're searching. That's what a map does. Than, simply extract the size of the list, if any.

List<String> val = testMap.get(key);
if(val != null){
    int size = val.size();
}

you say you know the key, so it's just map.get(key).size()

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top