I searched this question and found answers that used the Map.Entry like here, however the getValue() method returned an Object object instead of the type of object in the map. Like in the example below, I need it to return a User object so I can use a method from that class. When I tried using the while loop below however, it never leaves the loop. I was wondering the correct way to do this.
Map<String, User> users = new LinkedHashMap<String, User>();
users.put(name, user);
while(users.values().iterator().hasNext()){
currentUser = users.values().iterator().next();
currentUser.someMethod();
}
In Java HashMap, we can iterate through its keys, values, and key/value mappings.
If you're only interested in the keys, you can iterate through the keySet() of the map: Map<String, Object> map = ...; for (String key : map. keySet()) { // ... }
Using keyset() and value() method keyset(): A keySet() method of HashMap class is used for iteration over the keys contained in the map. It returns the Set view of the keys. values(): A values() method of HashMap class is used for iteration over the values contained in the map.
I was wondering the correct way to do this.
You should use the Map.Entry
type; you just need to provide type parameters to use with generics:
for (Map.Entry<String,User> entry : users.entrySet()) {
// entry.getValue() is of type User now
}
You're misusing the Iterator, and you're omitting the Generics specifications.
Iterator<User> it = users.values().iterator();
while (it.hasNext())
{
User currentUser = it.next();
currentUser.someMethod();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With