how to use HashMap in Java
HashMap is a type of Collection in Java, its function is almost the same as ArrayList, namely to organize and display data. HashMap uses key-value paired data types to organize its data. What distinguishes HashMap from ArrayList is that in HashMap, we do not input data sequentially, such as ArrayList, namely 0, 1, 2, 3, …. etc. . , so we use a mapping or MAP, based on a key as an index that we can fill freely and be a unique element that is different from each other, to access the value. So in this article, we will learn how to write a simple Java program using a HashMap as the collection.
Using HashMap in Java
In the following example program, we will create some data that we will enter in the HashMap, the data has its own key and value, and the sample data that we will create is as follows:
Key | Value |
Name | Fawad khan |
Age | 27 |
Salary | 100000 |
Address | Pakistan |
in the table above, the key is used as a key to display or access the value, the key in the HashMap you can fill in freely, this is what distinguishes the HasMap from the ArrayList, if the ArrayList displays the value, we need to access the index position, but in the HashMap, to access the value/value, we need to call the key.
In addition to the String data type, we can also use other Objects, such as List or Set. To be used as the Value.
Now that you know about the key and value functions, let’s try to discuss implementing HashMap in Java Programs. A simple example of using HashMap in java is as follows:
Example: how to use keys and values in java hashmap:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
package com.mycompany.javabasics; import java.util.HashMap; /**  *  * @author Fawadkhan  */ public class MapExamples {        public static void main(String[] args){        //create object for HashMap        HashMap<String,String> Data = new HashMap<>();        //store data in hashmap        Data.put("Name", "Fawad Khan");        Data.put("Age", "27");        Data.put("Salary", "100000");        Data.put("Address", "Pakistan");        //get data from hashmap        System.out.println(Data.get("Name"));        System.out.println(Data.get("Age"));        System.out.println(Data.get("Salary"));        System.out.println(Data.get("Address"));    } } |
Output:
Explanation:
To declare a HashMap object, the prefix syntax is as follows:
1 |
HashMap<Key, Value> object = new HashMap<>(); |
Key: Used as a Key To Call Value.
Value: These are the contents of the value that will be called by the key.
In the program, I create an initial object like this HashMap<String, String>Â which means, the Key and Value have a String data type, then to input data, you can use the put() function filled with the Key and Value, then to access the value, you can use the get() function inside the Key input to access the desired value.
You can differentiate the data types in Key and Value, for example<Integer, String>, <String, Integer>, <Integer, Integer>, <Boolean, Double>, etc .
Example: how to display all data at once in java hashmap:
In the previous program, we display data one by one using System.out.println(), to display all data at once, you are like in Array, you can use a for-each statement.
To display all data at once in java hashmap an example program is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
package com.mycompany.javabasics; import java.util.HashMap; import java.util.Map; /**  *  * @author Fawadkhan  */ public class MapExamples {        public static void main(String[] args){        //create object for HashMap        HashMap<Integer,String> Data = new HashMap<>();        //store data in hashmap        Data.put(1, "Fawad Khan");        Data.put(2, "hamza Khan");        Data.put(3, "Shaista");        Data.put(4, "sana");        Data.put(5, "khan");        Data.put(6, "john");        Data.put(7, "abc");        Data.put(8, "xyz");        for(Map.Entry map : Data.entrySet()){            System.out.println("Key: "+map.getKey()+ " Value = "+map.getValue());        }      }   } |
Output:
Program Explanation:
First of all, I import the library from java.util.Map, which is used to create a MAP on HashMap.
Here I use a for each loop, in the condition to display the Key and Value, I use Data.entrySet() , in the static class Map.Entry with a map object.
Then display all values ​​using the statement
1 |
System.out.println("Key: "+map.getKey()+" Value = "+map.getValue()) |
getKey is used to display the key and getValue() is used to display the Value.
If you only want to display the Key, change the line of code in the for-each to something like this:
1 2 3 4 5 |
for(Integer key : Data.keySet()){ Â Â Â Â Â Â Â Â Â Â Â System.out.println("Key: "+ key); Â Â Â Â Â Â Â } |
Output:
And if you want only the value to be displayed, change the code to something like this:
1 2 3 4 5 |
for(String value : Data.values()){ Â Â Â Â Â Â Â Â Â Â Â System.out.println("Value: "+ value); Â Â Â Â Â Â Â } |
Output:
Print Key and Value according to their respective data types, the values() and keySet() methods are used to calculate the number or size of the key and value.
In addition to String, Integer, Boolean data types, etc. We can also store values ​​with other Objects like List and Set . For that see the following program example.
Example: how to store list and set values in java hashmap:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
package com.mycompany.javabasics; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /**  *  * @author Fawadkhan  */ public class MapExamples {    public static void main(String[] args) {        List<String> Game = new ArrayList<>();        Game.add("Freefire");        Game.add("Car Parking");        Game.add("Need For Speed");        Game.add("Court Piece");        Game.add("Ludo King");        Game.add("Candy Crush");        Map<String, List<String>> Data = new HashMap<>();        Data.put("Game Name", Game);        for (Map.Entry map : Data.entrySet()) {            System.out.println(map.getKey() + " = " + map.getValue());        }    } } |
Output:
Explanation:
In the program, first, i create an object, for a group of keys, by writing the prefix
1 |
Map<String,List<String>> Data = new HashMap(); |
Then I use a Key with a String data type, and a Value inside a List with a String data type as well.
Next, i create an object from ArrayList to enter the values ​​or names of the games, by writing the code List<String>Game = new ArrayList<>();
Then input the data by using the add() function;
Next, I input data from the Map object, where “game name” is used as the key then the data in the game object is used as the value.
Then we display the data key and value, in System.out.println();