Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Collections

Java Maps: HashMap, LinkedHashMap and TreeMap

Emma 91 and Jack 78 go into a map. Putting Jack again with 82 replaces his mark, Priya gives null until getOrDefault turns it into 0, and remove leaves {Jack=82}. Then the same four puts print in three orders across HashMap, LinkedHashMap and TreeMap.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Collections

What you will learn

  • Store key and value pairs with put and read them with get
  • Explain why putting the same key again replaces the value
  • Handle a missing key with getOrDefault and containsKey
  • Pick HashMap, LinkedHashMap or TreeMap by the order you need

Before you start

  • From arrays to collections: the framework map
  • Java sets: HashSet, LinkedHashSet and TreeSet

A map is a collection of key and value pairs. The key could be a String, a number or almost anything, and so could the value. Here the key is a student's name and the value is their mark.

Put a pair, get it back

package org.studyeasy.s04l10;

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

public class Ex01_PutGet {
    public static void main(String[] args) {
        Map<String, Integer> marks = new HashMap<>();
        marks.put("Emma", 91);
        marks.put("Jack", 78);
        System.out.println("Jack: " + marks.get("Jack"));

        marks.put("Jack", 82);
        System.out.println("Jack: " + marks.get("Jack"));

        System.out.println("Priya: " + marks.get("Priya"));
        System.out.println("Priya: " + marks.getOrDefault("Priya", 0));

        System.out.println("Size: " + marks.size());
        System.out.println("Has Priya? " + marks.containsKey("Priya"));

        marks.remove("Emma");
        System.out.println("After remove: " + marks);
    }
}
Jack: 78
Jack: 82
Priya: null
Priya: 0
Size: 2
Has Priya? false
After remove: {Jack=82}
A map with two pairs, Emma to 91 and Jack to 78. put("Jack", 82) finds the existing key Jack and replaces 78 with 82, so there are still two keys. get("Priya") finds no key and returns null. "Emma"91 "Jack"78 82 put("Jack", 82) get("Priya") → null A key appears once: the same key replaces the value. Size stays 2.
keys on the left, values on the right; put is create or replace.

put is create or replace. Jack is already a key, so put("Jack", 82) swaps 78 for 82, and the map still has two keys. Priya was never put in, so get returns null. If you don't want null in your program, getOrDefault("Priya", 0) returns 0 instead. containsKey asks whether a key is there, and remove takes a pair out by its key. A printed map shows pairs in curly braces.

Careful with that null: int priya = marks.get("Priya"); tries to unbox null into an int and throws a NullPointerException.

Same puts, three orders

package org.studyeasy.s04l10;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;

public class Ex02_ThreeMaps {
    static void fill(Map<String, Integer> marks) {
        marks.put("Jack", 78);
        marks.put("Emma", 91);
        marks.put("Lucas", 85);
        marks.put("Priya", 64);
    }

    public static void main(String[] args) {
        Map<String, Integer> hash = new HashMap<>();
        Map<String, Integer> linked = new LinkedHashMap<>();
        Map<String, Integer> tree = new TreeMap<>();
        fill(hash);
        fill(linked);
        fill(tree);
        System.out.println("HashMap:       " + hash);
        System.out.println("LinkedHashMap: " + linked);
        System.out.println("TreeMap:       " + tree);
    }
}
HashMap:       {Priya=64, Lucas=85, Jack=78, Emma=91}
LinkedHashMap: {Jack=78, Emma=91, Lucas=85, Priya=64}
TreeMap:       {Emma=91, Jack=78, Lucas=85, Priya=64}

fill takes any Map (coding to the interface again) and puts the same four pairs in the same order. Maps come in the same three flavours as sets:

  • The HashMap is the fastest but doesn't keep a sequence. Here Priya comes out first; that order isn't promised.
  • The LinkedHashMap keeps the order you added them: Jack first, Priya last.
  • The TreeMap stores the keys as a tree and sorts by their natural order, alphabetical for names, so Emma is first. It can't sort a null key: tree.put(null, 1) throws a NullPointerException.

Which map do I reach for

You needUseOrder
Fast lookup (the usual case)HashMapnot promised
The order you put them inLinkedHashMapinsertion order
Sorted outputTreeMapsorted by key

put, get and getOrDefault work the same on all three. When in doubt, start with a HashMap. You don't need to memorise the syntax (an AI can write it), but knowing what each method does lets you read it. Next: stacks, queues and deques.

Keep going in Java · 52 of 79

Previous
Java Sorting with Comparable and Comparator
Next post
Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Related posts

Java equals and hashCode: Why a HashSet Needs Both

== asks if it's the very same object, equals compares values, and hashCode puts equal objects in the same HashSet bucket. Three small programs show what breaks when hashCode is missing.

From Arrays to Collections: The Java Collections Framework Map

An array of 3 students can't seat John, so Java throws Index 3 out of bounds. A List just grows. Then the map of the framework: List, Set and Queue under Collection, Map beside it, four behaviours in one program, and why the variable type should be the interface.

Java Wrapper Classes and Autoboxing

List<int> won't compile because a list holds objects only. Integer.valueOf puts 87 in a box and intValue takes it out, and add and get do it for you. Then two traps: 128 == 128 is false, and unboxing a null Integer throws a NullPointerException.

Java ArrayList: The Stretchy Array

add, add at an index, get, set, remove and contains on a list of courses and a cart, why Git at index 1 pushes SQL and Spring right, removing scores below 50 with an Iterator or removeIf, List.of that can't change, and the array inside that grows from 10 to 15.

On this page

  • Put a pair, get it back
  • Same puts, three orders
  • Which map do I reach for
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.