Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Javatutorial Java Map Example

Related Tutorials


 
 

Share on Google+Share on Google+

Java Map Example

Advertisement
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.

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

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: May 6, 2013

Related Tutorials

Discuss: Java Map Example  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com