Map is an Interface and which is available in java.util package and HashMap is an implementation of the Map interface. HashMap stores the data in key/value pair.
Output:
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
public class HashMapExample {
public static void main(String[] args) {
Map<Object, Object> map = new HashMap<Object, Object>();
// put the key and values in String format
map.put("1", "Java");
map.put("2", "Programming in C");
map.put("AI", "Lisp");
map.put("Script", "JavaScript");
System.out.println("Before Change - " + map.get("1"));
System.out.println("Key \t Value");
System.out.println("----------------");
// loop through the map data using Iterator Interface
Iterator<?> iterator = map.entrySet().iterator();
Map.Entry<String, String> entry = null;
while (iterator.hasNext()) {
entry = (Entry<String, String>) iterator.next();
System.out.println(entry.getKey() + "\t" + entry.getValue());
}
// Let's change the value for the key 1 and key 2
map.put("1", "OOP");
map.put("2", "Procedural");
System.out.println("After Change - " + map.get("1"));
System.out.println("After Change - " + map.get("2"));
}
}
Output:
Thanks for sharing this post Java HashMap .
ReplyDelete