I am trying to iterate only the first “n” values in my Map, is there any method available or i need to control it only with a count variable.
Below is an example, i have sorted a group of names belong to the same city. Now i only want the first 10 city and the person names in it.
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
List<String> list = entry.getValue();
// Display list of people in City
}
Is there a Map implementation that can hold fixed number of key,value pairs?
Please get some directions.
Thanks,
-Vijay Selvaraj
HashMapis unordered. This makes the question ill-posed (unless by “first” you mean “arbitrary”).If you want a consistent ordering of keys, you need to change the type of your map to a
SortedMap, such asTreeMap.Alternatively, if it’s the oldest elements you’re after (i.e. the ones you’ve inserted first), then
LinkedHashMapis the answer.As to actually getting the first
nelements, a loop with a counter is a pretty reasonable way to do it.