Java – How to use a foreach loop in Java to loop through the values in a HashMap

foreachhashmapjava

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?

Best Solution

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.