Search code examples
javahashmaplinkedhashmap

Get the first 5 elements of a Map in Java


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?


Solution

  • 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