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.
Structure
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.
Iteration in a HashMap
To iterate a hashmap, we can do as in the example below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
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> (); &lt 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!