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?
iinside of your loop. What do you think is happening?