user2731629 user2731629 - 1 month ago 8
Java Question

Infinite loop issue when Iterating List of Maps

My below code causing infinite loop. I am adding 3

maps
to the
ArrayList
and tried to Iterate the
list
of
Maps
. But I don't know what causing the infinite loop. I know I might did some silly mistake, but I couldn't figure it out. Can anyone help ?

package paddy.test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class Maptest {

public static void main(String[] args) {
// TODO Auto-generated method stub

Map < String, Integer > m = new HashMap<String, Integer>();

m.put("a", 1);
m.put("b", 1);
m.put("c", 1);
m.put("d", 1);
m.put("e", 1);

Map < String, Integer > m1 = new HashMap<String, Integer>();

m1.put("a", 1);
m1.put("b", 1);
m1.put("c", 1);
m1.put("d", 1);
m1.put("e", 1);

Map < String, Integer > m2 = new HashMap<String, Integer>();

m2.put("a", 1);
m2.put("b", 1);
m2.put("c", 1);
m2.put("d", 1);
m2.put("e", 1);

List<Map<String, Integer>> lm = new ArrayList<>();

lm.add(m);
lm.add(m1);
lm.add(m2);

Iterator<Map<String, Integer>> lmItr = lm.iterator();

while (lmItr.hasNext())
{
System.out.println(1);
}
}
}

Answer Source

You aren't consuming your iterator, instead you are printing a constant. Change

while (lmItr.hasNext())
{
    System.out.println(1);
}

to

while (lmItr.hasNext())
{
    System.out.println(lmItr.next());
}