HashMaps implement the Map interface. Now what a HashMap is,
is a member of the Java collections framework that stores objects in pairs,
where the first member of the pair is the key, while the second member of the
pair is the value. You can have duplicate values, but you can never have
duplicate keys. So let us create a HashMap that has integers as keys and
strings as values. Here is how we declare it:
HashMap<Integer, String> numbers = new
HashMap<Integer, String>();
Adding Items to HashMap
So to add items to the HashMap, we normally use the put()
method like this:
numbers.put(3, “Lucy”);
numbers.put(5, “Joseph”);
numbers.put(10, “Anthony”);
numbers.put(4, “Wayne”);
If you want to access the values referred to by the keys, we
use the get() method like this:
String name = numbers.get(10);
Figure 1: Adding items to a HashMap
Removing
Items from HashMap
If we want to remove an item from a HashMap, we use the
remove() method, in which we pass the key of the value we want to remove. So,
let’s say that in the above HashMap, we want to remove the key-value pair [5,
“Joseph”]. Here is how we’d do it:
numbers.remove(5);
Iterating
through a HashMap
There is a specific syntax for iterating through a HashMap.
For most people, including myself, the easiest way is to Google the syntax for
iterating through a HashMap and then copying and pasting it. However, over
time, you will get the hang of it. So here is the syntax with the above example
HashMap:
for(Map.Entry<Integer, String> entry: numbers.entrySet())
{
int key =
entry.getKey();
String value
= entry.getValue();
System.out.println(key
+ “: ” + value);
}Figure 2: Removing and iterating through items in a HashMap
That’s all for now with regards to HashMap. Just remember
that we use HasMaps when we want to store data with key value pairs. However,
it is vital to note that HashMaps aren’t ordered. What this means is that when
you iterate through a HashMap you may get one order several times, and after
several iterations, you may get another order. If you don’t require order in
your data, then use HashMaps. If, however, you require the data that you place
be of the same order always, you might want to use a sorted map, which we look
at in the next tutorial.
In case you have any questions or comments, please leave them
in the comments section below and I will make sure to address them.
Otherwise, stay safe until next time.
No comments:
Post a Comment