HashMap is part of the Collections framework of java. It stores the data in the form of key-value pairs. These values of the HashMap can be accessed by using their respective keys or the key-value pairs can be accessed using their indexes (of Integer type). HashMap is similar to Hashtable in java. The main difference between HashTable and HashMap is that Hashtable is synchronized but HashMap is not. Also, a HashMap can have one null key and any number of null values. The insertion order s not preserved in the HashMap. In a HashMap, keys and values can be added using the HashMap.put() method. We can also convert two arrays containing keys and values into a HashMap with respective keys and values.
Example:
keys = {1,2,3,4,5}
values = {"Welcome","To","Geeks","For","Geeks"}
HashMap = {1=Welcome, 2=To, 3=Geeks, 4=For, 5=Geeks}
Code
Java
import java.util.*;
import java.io.*;
class GFG {
public static HashMap map(Integer[] keys,
String[] values)
{
int keysSize = keys.length;
int valuesSize = values.length;
if (keysSize != valuesSize) {
throw new IllegalArgumentException(
"The number of keys doesn't match the number of values." );
}
if (keysSize == 0 ) {
return new HashMap();
}
HashMap<Integer, String> map
= new HashMap<Integer, String>();
for ( int i = 0 ; i < keysSize; i++) {
map.put(keys[i], values[i]);
}
return map;
}
public static void main(String[] args)
{
Integer[] keys = { 1 , 2 , 3 , 4 , 5 };
String[] values
= { "Welcome" , "To" , "Geeks" , "For" , "Geeks" };
Map m = map(keys, values);
System.out.println(m);
}
}
|
Output{1=Welcome, 2=To, 3=Geeks, 4=For, 5=Geeks}