Java: Create and Iterate Over Hashmap

6/22/2014 11:20:25 PM

A hashmap in Java is similar to a Dictionary in C#. One major difference is that in Java you can re-add or re-put the same key into the hash without throwing an error. The related value simply gets over-written.

//create hashmap
HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
hashMap.put(1, "user1");
hashMap.put(2, "user2");
hashMap.put(3, "user3");

for (Map.Entry<Integer, String> pair : hashMap.entrySet())
{
	Integer userId = pair.getKey();
	String username = pair.getValue();
	
	//do something with values
	System.out.println("UserId: " + userId.toString() + " Username: " + username);
}