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
  •  | 
  •  

Pregunta

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.

¿Fue útil?

Solución

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

testMap.get(key).size()

Otros consejos

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()

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top