Open In App
Related Articles

How to Convert Two Arrays Containing Keys and Values to HashMap in Java?

Improve Article
Save Article
Like Article

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. 


keys = {1,2,3,4,5}
values = {"Welcome","To","Geeks","For","Geeks"}
HashMap = {1=Welcome, 2=To, 3=Geeks, 4=For, 5=Geeks}



// Java program to convert two arrays containing keys and
// values into a HAshMap
import java.util.*;
class GFG {
    public static HashMap map(Integer[] keys,
                              String[] values)
        // two variables to store the length of the two
        // given arrays
        int keysSize = keys.length;
        int valuesSize = values.length;
        // if the size of both arrays is not equal, throw an
        // IllegalArgumentsException
        if (keysSize != valuesSize) {
            throw new IllegalArgumentException(
                "The number of keys doesn't match the number of values.");
        // if the length of the arrays is 0, then return an
        // empty HashMap
        if (keysSize == 0) {
            return new HashMap();
        // create a new HashMap of the type of keys arrays
        // and values array
        HashMap<Integer, String> map
            = new HashMap<Integer, String>();
        // for every key, value
        for (int i = 0; i < keysSize; i++) {
            // add them into the HashMap by calling the
            // put() method on the key-value pair
            map.put(keys[i], values[i]);
        // return the HashMap
        return map;
    // Driver method
    public static void main(String[] args)
        // create an array for keys
        Integer[] keys = { 1, 2, 3, 4, 5 };
        // create an array for value
        String[] values
            = { "Welcome", "To", "Geeks", "For", "Geeks" };
        // call the map() method over the keys[] array and
        // values[] array
        Map m = map(keys, values);
        // print the returned map


{1=Welcome, 2=To, 3=Geeks, 4=For, 5=Geeks}

Last Updated : 17 Dec, 2020
Like Article
Save Article
Similar Reads
Related Tutorials