0

I got a HashMap and want to iterate it. But somehow it is saying that I have incompatible types.

Required: java.util.Map.Entry <java.lang.String , java.lang.String>
 Found : java.lang.Object

Heres my code :

 Map hashmapMessagesKey = new HashMap<String,String>();
 for (Map.Entry<String, String> entry : hashmapMessagesKey.entrySet()) {

  }
Ahmet K
  • 713
  • 18
  • 42

2 Answers2

2

The declared type of your variable is the deciding factor, not the initialization. Your declared type is currently a raw Map-type but should be generic:

Map<String, String> hashmapMessagesKey = new HashMap<>();

Besides, depending on your use-case, the for-each method might be more readable as you can name the key and value instead of using entry.getKey() and entry.getValue():

hashmapMessagesKey.forEach((key, value) -> {
    // loop body
});
Nevay
  • 784
  • 5
  • 9
1

Your map defination seems to be wrong.

Map<String, String> map= new HashMap<String, String>();
Pshemo
  • 122,468
  • 25
  • 185
  • 269