bhylu.com

Advertisements

Java Select HashMap, LinkedHashMap or TreeMap

Map implementations can expose the same broad interface while providing different ordering and operation characteristics. Pick the guarantee the caller actually needs.

Understand the idea

Use HashMap when key lookup matters and order does not. LinkedHashMap is useful for predictable encounter order and also supports an explicitly configured access-order mode for specialised uses. TreeMap keeps keys in sorted order and offers navigational operations such as floorKey. Do not infer these contracts from the order of one small test run.

Run it locally

Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.

JDK and terminal setup

javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out Main

A worked example

Java 21+ · Main.java

import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        TreeMap<Integer, String> levels = new TreeMap<>();
        levels.put(5, "small");
        levels.put(12, "medium");
        levels.put(20, "large");
        System.out.println(levels.floorEntry(14));
        System.out.println(levels.firstKey());
    }
}

Expected output

12=medium
5

floorEntry chooses the greatest stored threshold that does not exceed fourteen. It does not require an exact key match. If the query were below every threshold, the entry result would be null and need handling. A sorted map can therefore model a threshold lookup without scanning a hand-maintained list of conditions.

Check the official Java documentation for detailed contracts and supported options.