Java Map Example

Map Interface adds keys to values. Every key in the Map Interface should be unique. It is part of java.util package. Each element in a map has a key and value. Each key-value pair is saved in a java.util.Map.Entry object. In the following example, a class HashMap is used to implement Map Interface . put() method is used to add elements to key and value pair. getKey() method and getValue()method are used to display the key and values. Map.Entry defines both of these methods.

Java Map Example

Map Interface adds keys to values. Every key in the Map Interface should be unique. It is part of java.util package. Each element in a map has a key and value. Each key-value pair is saved in a java.util.Map.Entry object. In the following example, a class HashMap is used to implement Map Interface . put() method is used to add elements to key and value pair. getKey() method and getValue()method are used to display the key and values. Map.Entry defines both of these methods.

Java Map Example


Map Interface adds keys to values. Every key in the Map Interface should be unique. It is part of java.util package. Each element in a map has a key and value. Each key-value pair is saved in a java.util.Map.Entry object.

Map Interface is implemented by following classes:

In the following example, a class HashMap is used to implement Map Interface . put() method is used to add elements to key and value pair. getKey() method and getValue()method are used to display the key and values. Map.Entry defines both of these methods.

Java Map Example:

package Collection;

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

public class MapExample {
	public static void main(String[] args) {
		Map Names = new HashMap(200);
		Names.put("IN", "India");
		Names.put("GB", "Great Britain");
		Names.put("FRs", "France");
		Names.put("IT", "Italy");
		Names.put("CA", "Canada");
		for (Map.Entry entry : Names.entrySet()) {
			System.out.println("Key = " + entry.getKey() + ", Value = "
					+ entry.getValue());
		}
	}

}

Output:

Key = GB, Value = Great Britain