0

I have question why I can't get this values

    HashMap<String, P> users = new HashMap<String, P>();
    users.put("john", new P("john"));

    List<String> arenaUsers = new ArrayList<String>();
    arenaUsers.add("john");

    for (String user : arenaUsers) {
        for (P p : users.get(user)) {
            System.out.println(p.getName());
        }
    }

I got error:

Can only iterate over an array or an instance of java.lang.Iterable

But I can't iterate Map, How I can fix it?

Trying
  • 14,004
  • 9
  • 70
  • 110
siOnzee
  • 91
  • 8

2 Answers2

0

In Map for one key you will get only one value, thats the cause of "Can only iterate over an array or an instance of java.lang.Iterable" this happens in the second for loop, which is useless as its only one value

for (P p : users.get(user))

Instead do as:

for (String user : arenaUsers) {
        if(users.containsKey(user))
           System.out.println(users.get(user).getName());
    }
}
user3020494
  • 712
  • 6
  • 9
0

here you class p does not implement Iterable so it can't be used inside the for loop. So to use it inside for loop you need to implement Iterable or use an existing collection which have already implemented Iterable i.e.

    Map<String, List<String>> map = new HashMap<String, List<String>>();
    List<String> l =new ArrayList<String>();l.add("stack");l.add("overflow");
    map.put("trying", l);
    for(String ss: map.get("trying")){
        System.out.println(ss);
    }

Here i have used List which implements Iterable and can be used in side the for loop.

Trying
  • 14,004
  • 9
  • 70
  • 110