Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch first 10 key value pairs in HashMap

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

like image 539
Vijay Selvaraj Avatar asked Mar 29 '12 10:03

Vijay Selvaraj


3 Answers

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.

like image 132
NPE Avatar answered Oct 04 '22 22:10

NPE


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.

like image 28
aioobe Avatar answered Oct 04 '22 21:10

aioobe


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());
}
like image 26
Churk Avatar answered Oct 04 '22 22:10

Churk