Java HashMap

A HashMap keeps data as key and value pairs, like a dictionary. You find a value very fast by its key. Keys are unique.

Basic use

import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> marks = new HashMap<>();

        marks.put("Riya", 88);
        marks.put("Aman", 72);
        marks.put("Meera", 95);
        marks.put("Aman", 75);          // same key: the value is replaced

        System.out.println(marks.get("Riya"));
        System.out.println(marks.get("Unknown"));              // null when missing
        System.out.println(marks.getOrDefault("Unknown", 0));
        System.out.println(marks.containsKey("Meera"));
        System.out.println(marks.containsValue(72));
        System.out.println(marks.size());

        marks.remove("Meera");
        System.out.println(marks);
    }
}
Output

88
null
0
true
false
3
{Aman=75, Riya=88}

Loop over a map

import java.util.Map;
import java.util.TreeMap;

public class Loop {
    public static void main(String[] args) {
        Map<String, Integer> stock = new TreeMap<>();     // TreeMap keeps the keys sorted
        stock.put("pen", 40);
        stock.put("book", 15);
        stock.put("bag", 5);

        for (Map.Entry<String, Integer> e : stock.entrySet()) {
            System.out.println(e.getKey() + " = " + e.getValue());
        }
        for (String key : stock.keySet()) {
            System.out.print(key + " ");
        }
        System.out.println();
        for (int value : stock.values()) {
            System.out.print(value + " ");
        }
        System.out.println();
        stock.forEach((k, v) -> System.out.println(k + " -> " + v));
    }
}
Output

bag = 5
book = 15
pen = 40
bag book pen
5 15 40
bag -> 5
book -> 15
pen -> 40

Count the words

import java.util.Map;
import java.util.TreeMap;

public class Words {
    public static void main(String[] args) {
        String text = "to be or not to be that is the question to be";
        Map<String, Integer> count = new TreeMap<>();

        for (String word : text.split(" ")) {
            count.merge(word, 1, Integer::sum);          // add 1, or start with 1
        }
        System.out.println(count);
    }
}
Output

{be=3, is=1, not=1, or=1, question=1, that=1, the=1, to=3}

Useful methods

MethodUse
put(k, v)Add or replace
get(k)Get the value (null when missing)
getOrDefault(k, d)Get the value or a default
putIfAbsent(k, v)Add only if the key is not there
computeIfAbsent(k, f)Make a value when the key is missing
merge(k, v, f)Combine values, great for counting
remove(k)Delete
containsKey(k)Check a key
keySet(), values(), entrySet()Views for looping

Which map?

ClassOrderSpeed
HashMapNo orderThe fastest. The default choice
LinkedHashMapOrder of insertFast
TreeMapSorted by keySlower, but sorted

Keys need equals and hashCode

The key class must have good equals() and hashCode() methods. String, Integer and records already have them.

import java.util.HashMap;
import java.util.Map;

record Point(int x, int y) { }

public class Keys {
    public static void main(String[] args) {
        Map<Point, String> places = new HashMap<>();
        places.put(new Point(1, 2), "School");
        System.out.println(places.get(new Point(1, 2)));
    }
}
Output

School

Note: A HashMap allows one null key and many null values. It is not thread safe, use ConcurrentHashMap when many threads write to it. Next: Java HashSet and LinkedList.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.