FAQ: Data Structures - Iterating over a HashMap


This community-built FAQ covers the “Iterating over a HashMap” exercise from the lesson “Data Structures”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Learn Java

FAQs on the exercise Iterating over a HashMap

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!


The items in the HashMap were inserted in this order…
restaurantMenu.put(“Turkey Burger”, 13);
restaurantMenu.put(“Naan Pizza”, 11);
restaurantMenu.put(“Cranberry Kale Salad”, 10);
But when we iterate through the list to print them out, the output is in this order (2nd and 3rd reversed)
A Turkey Burger costs 13 dollars.
A Cranberry Kale Salad costs 10 dollars.
A Naan Pizza costs 11 dollars.

Why doesn’t the Naan Pizza output second and the Cranberry Kale Salad output third?


if you check the documentation:


you see:

This class makes no guarantees as to the order of the map

i wouldn’t bother with understanding how hash maps are implemented, just know they aren’t ordered, and don’t have to be given we access values by key


If you do want to maintain the order, you can use a LinkedHashMap object instead! It has the exact same methods as the HashMap class you are currently using (it actually extends it), and it maintains the order of the components in the order that you add them!


In the example it used the key “name” yet in our exercise we used the key “item”. How did the program know what we meant if we didn’t define them as such?



for (String item : restaurantMenu.keySet())

you define the variable, the for loop then assigns each key to this variable

so Java does a lot of lifting.