Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use a foreach loop in Java to loop through the values in a HashMap?

I am trying to compile the following code:

private String dataToString(){     Map data = (HashMap<MyClass.Key, String>) getData();     String toString = "";     for( MyClass.Key key: data.keySet() ){         toString += key.toString() + ": " + data.get( key );     return toString; } 

I get an error in the for line that says:

 incompatible types found : java.lang.Object required: MyClass.Key 

The getData() method returns an Object (but in this case the Object returned has the HashMap structure). MyClass.Key is an enum that I have created for the purposes of my application (in another class file - MyClass).

When I created a foreach loop with the same structure in MyClass.java, I did not encounter this problem.

What am I doing wrong?

like image 282
troyal Avatar asked Jan 15 '09 19:01

troyal


People also ask

Can you use a forEach loop on a HashMap?

Note: The forEach() method is not the same as the for-each loop. We can use the Java for-each loop to loop through each entry of the hashmap.

Can you iterate through a HashMap Java?

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

How many ways we can iterate HashMap in Java?

There are generally five ways of iterating over a Map in Java.


2 Answers

A slightly more efficient way to do this:

  Map<MyClass.Key, String> data = (HashMap<MyClass.Key, String>) getData();    StringBuffer sb = new StringBuffer();   for (Map.Entry<MyClass.Key,String> entry : data.entrySet()) {        sb.append(entry.getKey());        sb.append(": ");        sb.append(entry.getValue());    }    return sb.toString(); 

If at all possible, define "getData" so you don't need the cast.

like image 165
Paul Tomblin Avatar answered Oct 11 '22 16:10

Paul Tomblin


Change:

Map data = (HashMap<MyClass.Key, String>) getData(); 

to

Map<MyClass.Key, String> data = (HashMap<MyClass.Key, String>) getData(); 

The problem is that data.keySet() returns a Collection<Object> if data is just a Map. Once you make it generic, keySet() will return a Collection<MyClass.Key>. Even better... iterate over the entrySet(), which will be a Collection<MyClass.Key, String>. It avoids the extra hash lookups.

like image 22
Craig P. Motlin Avatar answered Oct 11 '22 16:10

Craig P. Motlin