Arrays store items in an ordered collection and are accessed using an index number (which is an integer). HashMap stores items as key/value pairs. Values can be accessed by indexes, known as keys, of a user-defined type. Java HashMap class implements the map interface by using a hash table1.
A Java map is declared using the keyword Map
. This is followed by angle brackets <>
which containe data types for keys and values. The first parameter is the data type for the key and the second parameter is the data type for the mapped value. This is followed by the name of the map.
import java.util.HashMap; // import HashMap classimport java.util.Map; // import Map Interfaceclass MyClass {public static void main( String args[] ) {HashMap<Integer, String> shapes = new HashMap<Integer,String>(); // Create an ArrayList object with string data type}}
Below are some useful methods in the HashMap
class:
Add an item:
The put()
method is used to add a new key/value pair in a HashMap or it can replace the value of an existing key. First parameter is the key and second parameter is the mapped value.
shapes.put(6,"hexagon")
Access an item:
The get()
method takes a key as an input to access its associated value in the HashMap.
shapes.get(3)
Remove all items:
The clear()
method is used to remove all elements in a HashMap.
shapes.clear()
Remove an item:
The remove()
method takes a specific key as the input and removes its associated value in the HashMap.
shapes.remove(1)
Check if HashMap is empty:
The isEmpty()
method is to check whether the map is empty or not. It returns true if the map is empty and false if it is not.
shapes.isEmpty()
Size of HashMap:
The size()
method is used to find the number of key/value pairs in a HashMap.
shapes.size()
Below is a Java code implementation of a HashMap:
import java.util.HashMap; //importing the HashMap classimport java.util.Map; // importing the Map interfaceclass MyClass {public static void main( String args[] ) {HashMap<Integer,String> shapes = new HashMap<Integer,String>(); //create a HashMap with Integer keys and String Valuesshapes.put(4,"square"); // add square at key 4shapes.put(3,"triangle"); // add triangle at key 3shapes.put(6,"hexagon"); // add hexagon at key 6shapes.put(8,"octagon"); // add octagon at key 8shapes.put(5,"pentagon"); // add pentagon at key 5System.out.println(shapes); // print keys and mapped valuesshapes.remove(3); // removing value at key 3shapes.remove(5); // removing value at key 5System.out.println("Updated map:");System.out.println(shapes); // prints keys and mapped valuesshapes.put(4,"rhombus"); // replaces value at key 4 with rhombusSystem.out.println("Updated map:");System.out.println(shapes); // prints keys and mapped valuesSystem.out.println("Size of map is "+shapes.size());shapes.clear(); // removes all key/value pairs in the HashMapSystem.out.println("Updated map:");System.out.println(shapes); // prints keys and mapped values}}
Free Resources