LearnFrenzy
Sign in Take a free test

Java Programming · Topic 19 of 28

HashMap and TreeMap

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Coding Techniques

HashMap and TreeMap · Study material

EnumMap and immutable maps

EnumMap is the fastest map for enum keys and always iterates in declaration order. Map.of and Map.entry build small immutable maps – but do not rely on Map.of's iteration order, which can change between runs.

import java.util.EnumMap;
import java.util.Map;

enum Day { MON, TUE, WED, THU, FRI, SAT, SUN }

public class Main {
    public static void main(String[] args) {
        Map<Day, Integer> steps = new EnumMap<>(Day.class);     // array-backed, always in enum order, very fast
        steps.put(Day.SUN, 3000);
        steps.put(Day.MON, 8200);
        steps.put(Day.WED, 10400);
        System.out.println(steps);

        Map<String, Integer> codes = Map.of("IN", 91, "US", 1, "UK", 44);   // immutable; order NOT guaranteed
        System.out.println(codes.get("IN") + " " + codes.size());
        try {
            codes.put("JP", 81);
        } catch (UnsupportedOperationException e) {
            System.out.println("Map.of is immutable");
        }
        Map.Entry<String, Integer> e = Map.entry("FR", 33);
        System.out.println(e.getKey() + "=" + e.getValue());
    }
}

Output

{MON=8200, WED=10400, SUN=3000}
91 3
Map.of is immutable
FR=33

Safe removal and bulk updates

Map<String, Integer> stock = new HashMap<>(Map.of("pen", 0, "book", 12, "bag", 0, "lamp", 4));

stock.entrySet().removeIf(e -> e.getValue() == 0);      // ✔ remove while "iterating"
stock.values().removeIf(v -> v < 5);                     // ✔ views write through to the map
stock.replaceAll((k, v) -> v * 2);                       // ✔ update every value

// ✘ for (String k : stock.keySet()) if (...) stock.remove(k);   → ConcurrentModificationException

Counting and grouping idioms

// count
map.merge(word, 1, Integer::sum);
// count with getOrDefault (older style)
map.put(word, map.getOrDefault(word, 0) + 1);
// group into lists
groups.computeIfAbsent(dept, d -> new ArrayList<>()).add(employee);
// group into sets
tags.computeIfAbsent(post, p -> new TreeSet<>()).add(tag);
// keep the maximum per key
best.merge(student, score, Math::max);
// invert a map (value → key); duplicate values overwrite
original.forEach((k, v) -> inverted.put(v, k));

Map checklist

  • Declare as Map<K, V>; pick HashMap unless you need order.
  • Use immutable keys with equals/hashCode (String, Integer, records).
  • Prefer getOrDefault, merge and computeIfAbsent over null checks.
  • Iterate with entrySet when you need both key and value.
  • Use TreeMap for sorted output and range/nearest-key queries.
  • Use LinkedHashMap for predictable order and LRU caches.
  • Use ConcurrentHashMap for maps shared between threads.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About Java Programming

Java is one of the most used languages in the world – for enterprise software, Android apps, banking systems and backend services. This section covers core Java from syntax and data types to OOP, strings, arrays, exceptions, collections and multithreading, with clear explanations and practice questions for every topic.

Why it matters

  • Java is the main language in service-company placement tests and many product companies
  • OOP, String, collections and exception questions appear in nearly every Java interview
  • Strong core Java is the base for Spring Boot, Android and backend development
  • Java questions are common in university exams and certification tests

Who it is for

  • School students (Class 11–12 / ICSE computer applications) learning Java
  • College students (B.Tech, BCA, MCA) preparing for exams, labs and projects
  • Freshers preparing for placements, Java developer roles and technical interviews
  • Developers revising core Java before an interview

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • Java developer interviews
  • Service company tests
  • University exams
  • Certification exams
  • Government IT exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links