A hashmap is unique in that it’s similar to an array, but is made up of pairs of data: keys and values. Hashing converts large Strings to small Strings that represent the same String. The hashmaps keys and values can even be more than Strings – you could work with any pairing!
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Set;
For this example we will be using Iterator and Set as well.
HashMap <Integer, Boolean> isEven = new HashMap<Integer, Boolean>();
In my example, I’m using Integer keys with Boolean values to create isEven – a new hashmap!
isEven.put(3, false);
isEven.put(8, true);
isEven.put(45, false);
isEven.put(84, true);
isEven.put(100, true);
Add multiple elements to this new hashmap using its innate put method.
Set set = isEven.entrySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
Map.Entry mapEntry = (Map.Entry)iterator.next();
System.out.print("Key is "+ mapEntry.getKey() + " and value is ");
System.out.println(mapEntry.getValue() + ".\n");
}
Then display this content using both Iterator and Set to prepare set hashmap prints in a while loop. Perhaps a ForEach loop could have worked better upon reflection.
isEven.remove(3);
System.out.println("Map key and values after removal: \n");
iterator = set.iterator();
while (iterator.hasNext()) {
Map.Entry mapEntry = (Map.Entry)iterator.next();
System.out.print("Key is "+ mapEntry.getKey() + " and value is ");
System.out.println(mapEntry.getValue() + ".\n");
We can also remove specific hashmap entries with remove, playing counter to the put method we had originally begun with.
If you plugged this in and made your own hashmap, you may have noticed that it doesn’t spit out the same hashmap elements in the same .put order. Why is this? Write your answer in the comments below!
Follow my original code on my GitHub profile!
Credit to my partner Abdul Raza for his help!