Monday, February 16, 2015

Error in Iterrating over Entryset in Map

I just wrote a simple method to print the values of a given Map.
I gave the Map as a parameter for print Method and printing logic was implemented inside method.

But when i tried to iterate using simple "for loop" as below

--------------------------------------------------------------------------------------------------------

public static void printMapWithEntrySet(Map nameCount) {
for (Entry entry : nameCount.entrySet()) {
String key = entry.getKey().toString();

Integer value = entry.getValue();
System.out.println("key, " + key + " value " + value);
}
}

---------------------------------------------------------------------------------------------------------

there was a Type mismatch error
( "Type mismatch: cannot convert from element type Object to Map.Entry") 
showing in the highlighted line.

for (Entry entry : nameCount.entrySet()) {

I found the reason, it was very simple mistake. error is in the parameter.
I have not included type in Map definition the parameter.
It should be

Map nameCount

So the correct formation of the method would be

----------------------------------------------------------------------------------------------------------

public static void printMapWithEntrySet(Map nameCount) {
for (Entry entry : nameCount.entrySet()) {
String key = entry.getKey().toString();

Integer value = entry.getValue();
System.out.println("key, " + key + " value " + value);
}
}

----------------------------------------------------------------------------------------------------------

Because of that, Entry set object cannot cast the value for Entry and it comes as Object as stated below

----------------------------------------------------------------------------------------------------------

public static void printMapWithEntrySet(Map nameCount) {
for (Object entry : nameCount.entrySet()) {

}
}
----------------------------------------------------------------------------------------------------------


Without  the type definition of the Map , that is "" in  the parameter you can still implement the printing all values in a Map with using iterator.
So the code will looks like below.

----------------------------------------------------------------------------------------------------------
public static void printMap(Map nameCount) {

Iterator> it = nameCount.entrySet().iterator();
while (it.hasNext()) {
Entry pairs = (Entry) it.next();
System.out.println("key, " + pairs.getKey() + " value "
+ pairs.getValue());
}

}

----------------------------------------------------------------------------------------------------------

Here we have to use an Iterator. That is an additional burden.

No comments:

Post a Comment