1

I'm making a Java project for the university. I need to add in a String list the first 5 values of a Map, but I can't seem to find a way to iterate over just 5 elements and not all the elements like using an Iterator

Basically I have a Map declared as follows: Map<String, Integer> infl_numbers = new HashMap<>();

I want to do something like this:

for (short i =0;i<5;i++){
    // element = get i-th element of the Map
    // list.add(element)
}

Can anyone help me?

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
androidexpert35
  • 319
  • 1
  • 10
  • 4
    `HashMap` isn't ordered - the sort order of the elements is explicitly not defined. So you'll likely get different elements on every run of your application. – Hulk Nov 21 '20 at 18:51
  • 2
    Define what `first` means, Map's keys are backed by `Set` which by contract does not have defined order. – rkosegi Nov 21 '20 at 18:51
  • 1
    There are other types of Map that do provide ordering, though - have a look at `LinkedHashMap` which can provide insertion order or access order, depending on configuration. – Hulk Nov 21 '20 at 18:53
  • Does this answer your question? [How do I efficiently iterate over each entry in a Java Map?](https://stackoverflow.com/questions/46898/how-do-i-efficiently-iterate-over-each-entry-in-a-java-map) – rkosegi Nov 21 '20 at 18:54
  • 1
    Since you don't care about keys, you can directly iterate over values `infl_numbers.values().stream().limit(5).collect(Collectors.toList())` – rkosegi Nov 21 '20 at 18:57

2 Answers2

2

HashMap is the wrong class for this requirement. Since the elements in a HashMap are not ordered, you may get a different set of five elements each time. You should use LinkedHashMap which maintains the insertion order. Then, you can iterate the key set and get the first five elements with the help of a counter e.g.

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> map = new LinkedHashMap<>();
        map.put("One", 1);
        map.put("Two", 2);
        map.put("Three", 3);
        map.put("Four", 4);
        map.put("Five", 5);
        map.put("Six", 6);
        map.put("Seven", 7);
        map.put("Eight", 8);
        map.put("Nine", 9);
        map.put("Ten", 10);

        // Access first five elements
        int count = 0;
        Iterator<String> itr = map.keySet().iterator();
        while (itr.hasNext() && count < 5) {
            System.out.println(map.get(itr.next()));
            count++;
        }
    }
}

Output:

1
2
3
4
5
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
0

You can't do anything with an index (i = 0..4) directly on a Map because maps are generally unordered. Same with Sets. So all you can do is start processing a map, getting whatever items you get, and then stop after you've gotten 5 items:

int count = 0;
for (String key : infl_numbers.keySet()) {
    list.add(infl_numbers.get(key))
    count++;
    if (count == 5)
        break;
}

There are some types of Maps that are ordered. So if you have a reference to one of those rather than just a reference to a Map, the story is different, and depends on the subtype of Map you're dealing with.

CryptoFool
  • 21,719
  • 5
  • 26
  • 44