The use of HashMap is very common when working with values where it doesn’t matter the position of the item but the value of the key. A place where the HashMap is used very often is on parameterization methods.
For instance, imagine that you have a method that can receive a several numbers of parameters, each with distinct names.
In this case, you can use the HashMap with the concept of key = value and parameter name = parameter value.
It is important to understand that the HashMap works with the concept of key-value pairs, i.e., each element of your list has a key and associated value, so we can perform a quick search of the key that we want, without going trough the whole list or know the index/position we want to see.
The HashMap implements the interface Map <K,V>, Cloneable and Serializable, but what matters to us here is only that it implements Map. Note that the actual implementation of the Map <K,V> uses Generics to assign a key-value to the list. In other words, with the HashMap and Generics, we can specifically say what type of key (string, int, double, etc.) and the type of our value, which obviously can differ, without a problem.
To iterate a hashmap, we can do as in the example below:
import java.util.Collection; import java. util. HashMap; import java. util. Iterator; import java.util.Map; import java.util. Set; import java.util.Map.Entry public class TestaInterfaceMap { public static void main (String [] args) { Map <Integer, String> myHashMap = new HashMap <Integer, String> (); < myHashMap.put (1, "John Doe"); myHashMap.put (2, "Jane Doe"); myHashMap.put (3, "Will Smith"); Perforfim the iteration for (map.entry Entry <String,Integer> pair: myHashMap. entrySet object ()) { System.out.println (pair.getKey ()); System.out.println (pair.getValue ()); }
If you want to explore more about Java, visit our videos section! Below are some examples:
You can also follow some of the broadcasters who program in Java, like the two below:
Another cool way to find out interesting things about Java is to access our project page!
We’re thrilled to announce an exciting opportunity for you to win not one but two…
Acquiring practical skills is crucial for career advancement and personal growth. Education Ecosystem stands out…
Artificial Intelligence (AI) has been making significant strides in various industries, and the software development…
Another week to bring you the top yield platforms for three of the most prominent…
If you hold a large volume of LEDU tokens above 1 million units and wish…
It’s another week and like always we have to explore the top yield platforms for…
View Comments
Thanks for the simple explanation.