Library contents

Java Map.merge

Map.merge can initialize a count on the first scan and add one on later scans. LinkedHashMap keeps products in the order they first appeared.

A simple example

Map.merge

  1. Start with A, B, A
  2. Do this Count each key
  3. Result A has 2, B has 1
The second A increases the existing A count from one to two.

Syntax

Java syntax
counts.merge(code, 1, Integer::sum)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Count repeated product codes in input order

A reporting system receives a sequence of events or product codes with repetitions. Aggregate the values according to the required grouping and order so the report keeps the distinction between items and occurrences.

Result{B=2, A=1}
Main.java
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        Map<String, Integer> counts = new LinkedHashMap<>();
        for (String code : List.of("B", "A", "B")) {
            counts.merge(code, 1, Integer::sum);
        }
        System.out.println(counts);
    }
}
Output
{B=2, A=1}

Use a LinkedHashMap to retain the order of first appearance. Map.merge inserts the initial count and adds to an existing count when a code repeats.

Advertisements

Combine two deliveries for the same shelf

Two suppliers drop off crates of tea during one shift. The first delivery establishes the shelf count, and the second must add to the count without replacing the earlier delivery.

Result7
Main.java
import java.util.HashMap;

class Main {
    public static void main(String[] args) throws Exception {
        var crates = new HashMap<String, Integer>();
        crates.merge("Tea", 3, Integer::sum);
        crates.merge("Tea", 4, Integer::sum);
        System.out.println(crates.get("Tea"));
    }
}
Output
7

The first merge inserts three. The second calls the addition function with three and four.

Count north-door returns

A gallery receives entrance codes from four ticket desks. Count how often the specified code occurs when grouping the records. Which count belongs on that code’s row?

GivenN · S · N · N | count N
Worked result3

What to watch for

The combining function runs only when there is a previous non-null value.

Documentation for Map.merge