Java Map is part of collections framework. Java Map object is used to store key-value mappings. Java Map can’t contain duplicate keys however duplicate values are allowed.
HashMap uses hashCode() and equals() methods on keys for get and put operations. So HashMap key object should provide good implementation of these methods. This is the reason immutable classes are better suitable for keys, for example String and Integer.
package com.csi.collectionconcept;
import java.util.HashMap;
import java.util.Map;
public class HashMapConcept {
public static void main(String[] args) {
HashMap hm = new HashMap<>();
hm.put("ID", "121");
hm.put("NAME", "JERRY");
hm.put("SALARY", "96000.99");
hm.put("ADDRESS", "PUNE");
for (Map.Entry m : hm.entrySet()) {
System.out.println(m.getKey() + ": " + m.getValue());
}
}
}
Output: SALARY: 96000.99 ADDRESS: PUNE ID: 121 NAME: JERRY |
package com.csi.collectionconcept;
import java.util.Map;
import java.util.TreeMap;
public class TreeMapConcept {
public static void main(String[] args) {
TreeMap tm = new TreeMap<>();
tm.put("ID", "121");
tm.put("NAME", "JERRY");
tm.put("SALARY", "96000.99");
tm.put("ADDRESS", "PUNE");
for (Map.Entry m : tm.entrySet()) {
System.out.println(m.getKey() + ": " + m.getValue());
}
}
}
Output: ADDRESS: PUNE ID: 121 NAME: JERRY SALARY: 96000.99 |