Hash Maps in Java
Mon, Jan 23, 2023
One-minute read
Another very useful data structure is called a HashMap. This is simply a collection of data that is stored in the format key: value
, just like a dictionary. Some languages even call this structure a ‘dictionary’. The Hash part is because the key is passed into a method that “hashes” the letters in the key somehow and returns an integer. This integer is stored along with the key?? so that when you want to look up the key again, Java does the same hashing function, and can find the key you’re looking for very quickly O(n).
Some examples of things you could keep in HashMaps.
Map<String, String> words = new HashMap<String, String>();
words.add("atlas", "a book of maps");
words.add("ant", "a small insect");
list of word occurences in a text
Map<String, Integer> wordsCounts = new HashMap<String, Integer>();
words.add("atlas", 4);
words.add("ant", 5);
You can even store other data types inside maps, making them very flexible
Map<String, Patient> patient1 = new HashMap<String, Patient>();
patient1.add("Andy", new Patient("Andy", 3));
Some really useful methods
myMap.addAll(anotherList);
myMap.retainAll(anotherList);