javaif-statementwhile-loophashmapiterator

Looping through a HashMap using iterator does not stop for an if condition


A HashMap<Integer, Integer> has 10 entries but I only want to print 3 entries.

Code:

HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();
hm.put(2, 1);
hm.put(5, 3);
hm.put(7, 2);
hm.put(4, 1);
hm.put(6, 3);
hm.put(8, 2);
hm.put(9, 1);
hm.put(3, 3);
hm.put(1, 2);       
hm.put(0, 2);
Iterator <Map.Entry<Integer, Integer>> itr = hm.entrySet().iterator();
int n=4;
int i=0;
while(itr.hasNext()){
    if(i<n){
        Map.Entry<Integer, Integer> entry = itr.next();
        System.out.println(entry.getKey()+" repeated "+entry.getValue());
    }
    i++;
}

Output

0 repeated 2
1 repeated 2
2 repeated 1
3 repeated 3 //program will wait for 2 or 3 seconds here
4 repeated 1
5 repeated 3
6 repeated 3
7 repeated 2
8 repeated 2
9 repeated 1

Expecting output:

0 repeated 2
1 repeated 2
2 repeated 1
3 repeated 3

Why is the if-condition inside while-loop is not working?


Solution

  • You don't exit out of the loop once i becomes 4. Also, you don't consume/read the subsequent elements from the iterator as itr.next() is inside the if block. So, it keeps incrementing i until it overflows to Integer.MIN_VALUE (-2147483648) and this takes a few seconds (which you have observed).

    At this point the condition of the if block becomes true (i < n) and hence it starts printing the other elements from the iterator.

    You can print the value of i to see this.

    System.out.println(entry.getKey()+" repeated "+entry.getValue() +". The value of i is: " + i);
    

    Prints,

    0 repeated 2. The value of i is: 0
    1 repeated 2. The value of i is: 1
    2 repeated 1. The value of i is: 2
    3 repeated 3. The value of i is: 3
    4 repeated 1. The value of i is: -2147483648
    5 repeated 3. The value of i is: -2147483647
    6 repeated 3. The value of i is: -2147483646
    7 repeated 2. The value of i is: -2147483645
    8 repeated 2. The value of i is: -2147483644
    9 repeated 1. The value of i is: -2147483643