How do I iterate through an entire HashMap

孤者浪人 提交于 2019-12-11 18:33:54

问题


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
}


来源:https://stackoverflow.com/questions/13078077/how-do-i-iterate-through-an-entire-hashmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!