How do I iterate through an entire HashMap

2019-08-28 23:28发布

问题:

If the method I need to use looks like this...

public void printMessages(Message mm) {
}

How do I iterate through the entire HashMap that looks like this...

HashMap<String, ArrayList<User>> hM = new HashMap<>();

to send each User the toString message generated by the Message mm? I'm stuck thanks for the advice.

回答1:

To iterate over a map, use a foreach on the entrySet()

Map<K, V> map;
for (Map.Entry<K, V> entry : map.entrySet()) {
    // do something with the key/value
    K key = entry.getKey();
    V value = entry.getValue();
}


However, in your case I think you may actually want this:

String message;
Map<String, List<User>> hM;

List<User> usersForMessage = hM.get(message);
for (User user : usersForMessage) {
    // send "message" to "user"
    user.sendMessage(message);  // for example
}