简体   繁体   中英

How do I iterate through an entire HashMap

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM