How do I iterate through a Java Linked Hash map?
Solution 1
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();
}
Solution 2
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
}
Solution 3
The easiest way to iterare is using for. In a LinkedHashMap it would be like this:
private static LinkedHashMap<Integer, String> dataBase = new LinkedHashMap<Integer, String>();
for(Integer key : dataBase.keySet()) {
String ret = dataBase.get(key);
}
Solution 4
Each time you call .iterator()
, it gives you a brand new iterator at the first element.
You need to call .iterator()
once and store it in a local variable.
user1875021
Updated on June 29, 2020Comments
-
user1875021 almost 4 years
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(); }
-
user1875021 over 11 yearsSo like
Iterator temp = users.values.iterator();
? -
user1875021 over 11 yearsThen would I be able to do
entry.getValue().someUserMethod();
-
user207421 over 11 years@user1875021 As he's already told you that
entry.getValue()
is of typeUser
, the answer to that should be obvious. You could always try it. -
user1875021 over 11 yearsAh I see. I tried that, but wasn't familiar about Generics so I kept getting an Object. Thanks
-
Sergey Kalinichenko over 11 years@user1875021 Absolutely!
entry.getValue()
is of typeUser
, you can do anything you would like with it. -
user207421 about 10 yearsYou don't have to remove anything. You just have to iterate correctly. This code will remove and skip every second element. -1
-
findusl over 4 yearsWhat is supposed to be the advantage of using
entrySet()
? He doesn't use the key, so iterating overvalues()
totally get's the job done or? -
Sergey Kalinichenko over 4 years@findusl If OP isn't planning on using the key, of course he should use
values()
; perhaps it would be slightly more economical in terms of CPU cycles. I was under impression that the code inside the loop wasn't a complete fragment, and wanted to leave OP some flexibility to access the key along with the value.