In Java using HashMap we can store data using custom indexes. In HashMap an Index can be any object type. And for each object index there is a value.
Importing in package declaration
import java.util.HashMap;
Variable declaration:
HashMap<String, String> studentIds = new HashMap<String, String>();
Adding Items:
To add items in HashMap simply use the put(java.lang.Object, java.lang.Object). When you declare a HashMap using specific type of class, you can only add or get items from HashMap using that specific type only.
import java.util.HashMap
public class HashMapExample{
public static void main(String[] args){
HashMap<String, String> studentIds = new HashMap<String, String>();
studentIds.put("20191010115", "Jennifer Lopez");
studentIds.put("20192010114", "Mira Chitra");
studentIds.put("20202809779", "Jita Forge");
}
}
Note that putting multiple items in same key, will replace the previous values;
Accessing Items:
To access a values, simple use the get(java.lang.Object) method. If the corresponding doesn’t exist null will be returned
String name = studentIds.get("20191010115");
Removing Items:
The remove(java.lang.Object) method is there to simply remove a data pair in the HashMap.
studentIds.remove("20191010115");
To clear the HashMap, ie delete all data in it, call the clear() method
studentIds.clear();
Getting the Size of HashMap:
The size() method returns the size of the HashMap. Note that, it only counts the number of data pairs in it, not the size in bytes. Example:
studentIds.size();
Iterating through HashMap
Sometimes, we need to read all the keys and respected references in it. To iterate a HashMap use keySet() in for.
for (String id: studentIds.keySet()){
System.out.println(id);
}
If you also want to print the reference variable for the key
for (String id: studentIds.keySet()){
System.out.println(id + "->" + studentIds.get(id));
}
To get only the values:
for (String name: studentIds.values()){
System.out.println(name);
}