Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I iterate through a Java Linked Hash map?

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();
}
like image 827
user1875021 Avatar asked Dec 06 '12 01:12

user1875021


People also ask

Can you iterate a HashMap?

In Java HashMap, we can iterate through its keys, values, and key/value mappings.

How do I iterate through a key in a HashMap?

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()) { // ... }

Do you know HashMap How do you iterate keys and values in HashMap?

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.


2 Answers

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
}
like image 153
Sergey Kalinichenko Avatar answered Oct 19 '22 23:10

Sergey Kalinichenko


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();
}
like image 31
user207421 Avatar answered Oct 19 '22 23:10

user207421