Iterating with HashMap


Iterating with HashMap

I have a silly question to ask for HashMap

How do I know which Item this line of code is targeting since this HashMap have both String and Integer.

	for (String item : restaurantMenu.keySet()){

			System.out.println("A " + item + " costs " + restaurantMenu.get(item) + " dollars.");


A Turkey Burger costs 13 dollars.
A Cranberry Kale Salad costs 10 dollars.
A Naan Pizza costs 11 dollars.

So, this hashMap is printing “item” twice! In the output you can clearly see that it gets the string part of the hashmap and then the integer part of the hashmap… i’m not understanding the code where -

System.out.println(item) will only print out the string part of the hashmap and the code
System.out.println(restaurantMenu.get(item); will print only the Integer value of the hashmap.

please help


Do you mean that keys and values in the hashmap have different types? There’s no mixing those up, they do different things. Would you mix up the name and phone number of a person when looking up someone in a phone directory?

If you have “Turkey Burger” you could probably look up 13 fairly easily, but how would you find “Turkey Burger” if you had 13? That would take more work (try it), they’re clearly very different.

If you wanted a two-way mapping then you’d have to insert they key-value pairs twice, with one of the insertions being in the other order, or perhaps two separate hashmaps.