A
Map
is an object that maps keys to values. A map cannot contain duplicate keys, each key can map to at most one value. This interface takes the place of the
Dictionary class, which was a totally abstract class rather than an interface.
The Java platform contains three general-purpose Map implementations:
Java HashMap Implementation,
TreeMap In Java - java.util.TreeMap, and
LinkedHashMap In Java with Code Example.
Map Methods :
Map
import java.util.HashMap;
import java.util.Map;
class MapTest
{
public static void main(String arg[])
{
Map<String, String> m = new HashMap<String, String>();
Map<String, String> m1 = new HashMap<String, String>();
System.out.println("Map objects equal : " + m.equals(m1)); // Equals method
m.put("8", "Prakash"); // Put method
m.put("31", "Shabaz");
m.put("12", "Raj");
m.put("14", "Praveen");
m.put("5", "Gopi");
System.out.println("Map Elements : " + m); // Display map elements
System.out.println("Size of Map : " + m.size());
System.out.println("Key contains : " + m.containsKey("31")); // LINE A
System.out.println("Value contains : " + m.containsValue("Raj")); // LINE B
System.out.println("Gets the value of key : " + m.get("14")); // LINE C
System.out.println("Hash code for map : " + m.hashCode());
System.out.println("Is map empty : " + m.isEmpty());
System.out.println("Removes the key value : " + m.remove("12")); // LINE D
System.out.println("Key set : " + m.keySet()); // LINE E
System.out.println("Collection values : " + m.values()); // LINE F
m1.putAll(m); // LINE G
m.clear();
System.out.println("Map after clear : " + m);
System.out.println("All data of m is put into m1 map : " + m1);
System.out.println("Entry set : " + m1.entrySet());
}
}
OUTPUTMap objects equal : true
Map Elements : {5=Gopi, 31=Shabaz, 8=Prakash, 14=Praveen, 12=Raj}
Size of Map : 5
Key contains : true
Value contains : true
Gets the value of key : Praveen
Hash code for map : 867799845
Is map empty : false
Removes the key value : Raj
Key set : [5, 31, 8, 14]
Collection values : [Gopi, Shabaz, Prakash, Praveen]
Map after clear : {}
All data of m is put into m1 map : {5=Gopi, 31=Shabaz, 8=Prakash, 14=Praveen}
Entry set : [5=Gopi, 31=Shabaz, 8=Prakash, 14=Praveen]
DESCRIPTIONIn this program, all the Map
methods are applied on map object. The map is of type HashMap
. It contains five elements.
THINGS TO TRY
- At
LINE A
replace 31
by 5
to see that output is true
. Which means key
5
is present in map. Enter any other key
which is not in the map to return false
. The same thing repeat for value
at LINE B
.
- At
LINE C
give any key
to return the value
associated with that key. It returns null
if the key does not exist in map.
- at
LINE D
, remove
is used to delete the element from map. Try with key 5
.