Java Collections: Map & Set

Map — key/value pairs

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

Map<String, Integer> marks = new HashMap<>();

marks.put("Sita", 88);
marks.put("Ram", 74);
marks.put("Sita", 92);        // replaces the old value

System.out.println(marks.get("Sita"));            // 92
System.out.println(marks.get("Unknown"));         // null
System.out.println(marks.getOrDefault("X", 0));   // 0
System.out.println(marks.containsKey("Ram"));     // true
System.out.println(marks.size());                  // 2

marks.remove("Ram");

Iterating a Map

Java
for (Map.Entry<String, Integer> e : marks.entrySet()) {
    System.out.println(e.getKey() + ": " + e.getValue());
}

marks.forEach((name, mark) -> System.out.println(name + " = " + mark));

for (String name : marks.keySet())    { }
for (int mark : marks.values())        { }

Handy Map methods

Java
marks.putIfAbsent("Hari", 60);
marks.merge("Sita", 5, Integer::sum);        // add 5 to the existing value
marks.computeIfAbsent("Gita", k -> 0);

merge and computeIfAbsent replace the classic "check-if-null-then-put" dance — especially useful for counting:

Java
Map<String, Integer> counts = new HashMap<>();
for (String word : words) {
    counts.merge(word, 1, Integer::sum);
}

Map variants

Class Ordering
HashMap none (fastest — the default)
LinkedHashMap insertion order
TreeMap sorted by key

Set — unique values, no duplicates

Java
import java.util.HashSet;
import java.util.Set;

Set<String> tags = new HashSet<>();

tags.add("nepali");
tags.add("fiction");
tags.add("nepali");        // ignored — already present

System.out.println(tags.size());            // 2
System.out.println(tags.contains("fiction")); // true
tags.remove("fiction");

Same variants: HashSet (unordered), LinkedHashSet (insertion order), TreeSet (sorted).

Removing duplicates from a list

Java
List<String> withDupes = List.of("a", "b", "a", "c");
List<String> unique = new ArrayList<>(new LinkedHashSet<>(withDupes));
// [a, b, c] — order preserved

equals and hashCode

HashMap and HashSet find objects using hashCode() and equals(). If you use your own class as a key, override both — or lookups will silently fail:

Java
public record Student(String name, int roll) {}   // records do this for you

That is another good reason to reach for records.