java hash map demo

Hashtable in Java maps keys to values, it permits null key and null values. In the demo below, the key is of string type and the value is of integer type. After the hash map is defined, you can use the put to put a key and a value to the hash map. To loop through the hash map, using the entrySet to get each sets and then loops through each entry in the hash map.

For demonstration purpose, the values in this demo are integers, but it could any other types of data, either be primitive types or any other object types such as a list or a customer object type.

import java.util.HashMap;
import java.util.Map.Entry;

public class HashMapDemo {
	public static void main(String args[]) {
		HashMap<String, Integer> scores = new HashMap<String, Integer>();
		scores.put("Amy", 74);
		scores.put("Ben", 82);
		scores.put("Carol", 80);
		scores.put("Denny", 92);
		scores.put("Edward", 91);
		for(Entry<String, Integer> entry : scores.entrySet()) {
		    String key = entry.getKey();
		    Integer value = entry.getValue();
		    System.out.println(key + " : " + value);
		System.out.println("\nAdd 10 points for Amy.\n..........................");
		scores.put("Amy", scores.get("Amy") + 10);
		System.out.println("Amy's new score: " + scores.get("Amy"));


Denny : 92
Ben : 82
Amy : 74
Carol : 80
Edward : 91

Add 10 points for Amy.
Amy's new score: 84

Search within Codexpedia

Custom Search

Search the entire web

Custom Search