Counting and grouping with maps
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Two jobs come up again and again in real programs: counting how many times each thing appears, and grouping things that share something, like students of the same branch. A map does both: the key is the thing, and the value is its count or its group.
Counting with a map
A frequency map is a map from an item to how many times it appears, such as a word to its count. You build it in one pass: for every item, read the old count, add 1 and store it again.
To count, use the item as the key and its count as the value. A new item has no count yet, so getOrDefault(item, 0) supplies 0. Below, a sentence is split into words and each word is counted.
Example 1 · Word count with getOrDefault
import java.util.HashMap;import java.util.Map;import java.util.TreeSet;
public class WordCountDemo { public static void main(String[] args) { String text = "the cat and the dog and the bird"; Map<String, Integer> count = new HashMap<>();
for (String word : text.split(" ")) { count.put(word, count.getOrDefault(word, 0) + 1); }
for (String word : new TreeSet<>(count.keySet())) { System.out.println(word + ": " + count.get(word)); } System.out.println("Different words: " + count.size()); }}and: 2 bird: 1 cat: 1 dog: 1 the: 3 Different words: 5
What this code does
- For a new word,
getOrDefaultgives 0, so the count becomes 1. For a repeated word, it gives the old count. - The
TreeSetof keys prints the words in A-Z order, every time.
The counting line is count.put(word, count.getOrDefault(word, 0) + 1);. Without the default, count.get(word) + 1 would crash on the first word, because get returns null and Java cannot add 1 to null.
merge: count or add up in one line
merge(key, value, function) puts value for a new key. For an existing key it calls the function with the old value and value, and stores the result. One call works for the first and for every later item.
merge does the same job in one call. The function is a lambda that combines two values. Below, it counts votes for a class rep, and then adds up the amounts each customer spent.
Example 2 · merge: counting class-rep votes
import java.util.HashMap;import java.util.Map;import java.util.TreeSet;
public class VoteDemo { public static void main(String[] args) { String[] votes = {"Meera", "Arjun", "Meera", "Kabir", "Arjun", "Meera", "Riya"}; Map<String, Integer> tally = new HashMap<>();
for (String name : votes) { tally.merge(name, 1, (oldCount, one) -> oldCount + one); }
String winner = null; for (String name : new TreeSet<>(tally.keySet())) { int v = tally.get(name); System.out.println(name + ": " + v + " vote(s)"); // strict > keeps the first name in A-Z order on a tie if (winner == null || v > tally.get(winner)) { winner = name; } } System.out.println("Class rep: " + winner); }}Arjun: 2 vote(s) Kabir: 1 vote(s) Meera: 3 vote(s) Riya: 1 vote(s) Class rep: Meera
What this code does
- The first vote for a name puts 1. Every later vote calls the lambda with the old count and 1, and stores the sum.
- Because the loop goes in A-Z order and uses strict
>, a tie is won by the name that comes first alphabetically. The rule is written in a comment.
Example 3 · merge: running totals per customer
import java.util.HashMap;import java.util.Map;import java.util.TreeSet;
public class StoreSpendDemo { public static void main(String[] args) { String[] payer = {"Riya", "Arjun", "Riya", "Meera", "Arjun", "Riya"}; int[] amount = {40, 25, 60, 35, 120, 15};
Map<String, Integer> spent = new HashMap<>(); for (int i = 0; i < payer.length; i++) { spent.merge(payer[i], amount[i], (total, more) -> total + more); }
int grandTotal = 0; for (String name : new TreeSet<>(spent.keySet())) { System.out.println(name + " spent Rs. " + spent.get(name)); grandTotal += spent.get(name); } System.out.println("Store earned Rs. " + grandTotal); }}Arjun spent Rs. 145 Meera spent Rs. 35 Riya spent Rs. 115 Store earned Rs. 295
What this code does
mergeis not only for counting. Here the value passed in is the amount, so each customer's total grows by that amount.- Riya's three payments, 40 + 60 + 15, end up as one entry of 115.
Count with count.merge(word, 1, (oldCount, one) -> oldCount + one); and add up money with spent.merge(name, amount, (total, more) -> total + more);. The function decides how to combine: sum, maximum, or anything else.
The other one-call methods, such as compute, computeIfPresent and replaceAll, are in Modern Map methods (opens in a new tab).
Predict the output
What does merge store?
Read each program and pick what it prints.
Round 1 of 3
Counting three pens with merge.
Grouping: one key, many values
A grouping map is a map whose value is a list of all the items that share one key, such as a branch name and the list of its students.
To group, make the value a list: Map<String, List<String>>. computeIfAbsent(key, k -> new ArrayList<>()) creates the list the first time and returns the list that is in the map. Below, students are grouped by branch.
Example 4 · Grouping with computeIfAbsent
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.TreeSet;
public class BranchGroupDemo { public static void main(String[] args) { String[] students = {"Asha:CSE", "Bala:ECE", "Chitra:CSE", "Dev:MECH", "Esha:ECE", "Farhan:CSE"}; Map<String, List<String>> byBranch = new HashMap<>();
for (String s : students) { String[] parts = s.split(":"); String name = parts[0]; String branch = parts[1]; byBranch.computeIfAbsent(branch, b -> new ArrayList<>()).add(name); }
for (String branch : new TreeSet<>(byBranch.keySet())) { List<String> names = byBranch.get(branch); System.out.println(branch + " (" + names.size() + "): " + names); } }}CSE (3): [Asha, Chitra, Farhan] ECE (2): [Bala, Esha] MECH (1): [Dev]
What this code does
- For the first
CSEstudent,computeIfAbsentcreates an empty list, stores it and returns it, andaddputs Asha in it. - For Chitra and Farhan, it returns the same
CSElist, so they join Asha. Inside each list, names stay in input order.
Example 5 · Mistake: chaining add after putIfAbsent
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;
public class PutIfAbsentTrap { public static void main(String[] args) { Map<String, List<String>> rooms = new HashMap<>();
rooms.putIfAbsent("A-101", new ArrayList<>()).add("Riya"); System.out.println(rooms); }}Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.List.add(Object)" because the return value of "java.util.Map.putIfAbsent(Object, Object)" is null at PutIfAbsentTrap.main(PutIfAbsentTrap.java:10)
What this code does
putIfAbsentreturns the old value.A-101had no list, so it stores the new list and returnsnull. Calling.addonnullcrashes.- Use
rooms.computeIfAbsent("A-101", r -> new ArrayList<>()).add("Riya");: it returns the list that is in the map.
If the key is missing, computeIfAbsent runs the lambda to make a new list, puts it in the map and returns it. If the key is there, it just returns the existing list. Either way, you can call .add(...) on the result straight away.
Order of execution
What computeIfAbsent does for a new key
Tap the steps in the order they happen.
putIfAbsent(key, new ArrayList<>()).add(x). When putIfAbsent adds a new list, it returns null, so .add throws a NullPointerException.Showing the results
A HashMap gives no promised order, so a report must choose its own. Loop over new TreeSet<>(map.keySet()) for A-Z order, or over a fixed array of labels with getOrDefault(label, 0), which also shows labels with count 0.
import java.util.*;
public class GradeReport { public static void main(String[] args) { Map<String, Integer> counts = new HashMap<>(); for (String g : new String[] {"B", "A", "B", "C", "A", "B"}) { counts.put(g, counts.getOrDefault(g, 0) + 1); } for (String label : new String[] {"A", "B", "C", "F"}) { System.out.println(label + ": " + counts.getOrDefault(label, 0)); } }}A: 2 B: 3 C: 1 F: 0
To find the most frequent item, loop over entrySet() and keep the entry with the biggest value, as in the previous lesson. Decide what happens on a tie and write it in a comment.
Example 6 · Full example: class result analysis
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;
public class ResultAnalysisDemo { static String grade(int marks) { if (marks >= 80) { return "A"; } else if (marks >= 60) { return "B"; } else if (marks >= 35) { return "C"; } return "F"; }
public static void main(String[] args) { String[] names = {"Asha", "Bala", "Chitra", "Dev", "Esha", "Farhan", "Gita", "Hari"}; int[] marks = {91, 67, 45, 82, 74, 68, 63, 52};
Map<String, Integer> gradeCount = new HashMap<>(); Map<String, List<String>> gradeNames = new HashMap<>();
for (int i = 0; i < names.length; i++) { String g = grade(marks[i]); gradeCount.merge(g, 1, (a, b) -> a + b); gradeNames.computeIfAbsent(g, k -> new ArrayList<>()).add(names[i]); }
String[] order = {"A", "B", "C", "F"}; String mostCommon = order[0]; for (String g : order) { int c = gradeCount.getOrDefault(g, 0); System.out.println(g + ": " + c + " " + gradeNames.getOrDefault(g, List.of())); if (c > gradeCount.getOrDefault(mostCommon, 0)) { mostCommon = g; } } System.out.println("Most common grade: " + mostCommon); }}A: 2 [Asha, Dev] B: 4 [Bala, Esha, Farhan, Gita] C: 2 [Chitra, Hari] F: 0 [] Most common grade: B
What this code does
- One loop fills two maps:
mergecounts each grade, andcomputeIfAbsentcollects the names. - Looping over the fixed
orderarray prints the grades in A, B, C, F order.getOrDefaultshowsF: 0 []even though nobody failed. List.of()is an empty list, used as the default when a grade has no names.
Next step
Check your understanding
12 quick questions