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
How to fetch first 10 key value pairs in
HashMap
HashMap
is 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 as TreeMap
.
Alternatively, if it's the oldest elements you're after (i.e. the ones you've inserted first), then LinkedHashMap
is the answer.
As to actually getting the first n
elements, a loop with a counter is a pretty reasonable way to do it.
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.
The closest thing you'll find using only the standard Collections API (which still is slightly worse than a counter variable IMO) is the following:
List<Map.Entry<String, List<String>> entryList =
new ArrayList<Map.Entry<String, List<String>>(map.entrySet());
for (Map.Entry<String, List<String>> entry : entryList.subList(0, 10)) {
List<String> list = entry.getValue();
// Display list of people in City
}
The lengthy type parameters could be avoided either by using the fancy diamond from Java 7:
List<Map.Entry<String, List<String>> entryList = new ArrayList<>(map.entrySet());
or by using iterating over the keys and .get
the corresponding values.
List<List<string>> list = new ArrayList<List<String>>();
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
if (list.size() > 9) break;
list.add(entry.getValue());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With