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