Nested HashMap
Part of the Logic & Flow section of Coddy's Java journey — lesson 19 of 59.
A nested HashMap is a HashMap whose values are themselves HashMaps. This lets you organize complex data hierarchically. For example, you can have an outer HashMap that maps categories (like "Electronics" or "Furniture") to inner HashMaps that hold products and their prices.
Create a nested HashMap: categories -> (items -> prices)
HashMap<String, HashMap<String, Integer>> inventory = new HashMap<>();Add a category "Electronics" with an empty inner HashMap
inventory.put("Electronics", new HashMap<>());Add an item "Laptop" with price 1200 into "Electronics"
inventory.get("Electronics").put("Laptop", 1200);Check if the outer map is empty and print its size
System.out.println(inventory.isEmpty());
// Output: false
System.out.println(inventory.size());
// Output: 1In this example, the outer map has one key ("Electronics") which maps to an inner HashMap containing the key "Laptop" and its value 1200.
Challenge
EasyCreate a method named <b>printNestedInventory</b> that takes a nested HashMap called inventory as input. In this inventory:
- Keys are categories (e.g., "Electronics", "Furniture").
- Values are inner HashMaps where keys are product names and values are their prices.
Your method should print the inventory in the following format:
- For each category, print
Category: <name> - If the category has products, print each one as
Product: <name>, Price: <price>(with 2 spaces of indentation) - If the category has no products, print
(No products)(with 2 spaces of indentation)
Example output:
Category: Electronics
Product: Laptop, Price: 1200
Product: Smartphone, Price: 800
Category: Furniture
Product: Chair, Price: 50
Product: Table, Price: 150
Category: EmptyCategory
(No products)Note: HashMap does not guarantee iteration order, so the order of categories and products in your output may differ from the example above — this is expected.
Note: You will need to import java.util.Map in addition to the other provided imports.
Cheat sheet
A nested HashMap is a HashMap whose values are themselves HashMaps, allowing hierarchical data organization.
Create a nested HashMap:
HashMap<String, HashMap<String, Integer>> inventory = new HashMap<>();Add a category with an empty inner HashMap:
inventory.put("Electronics", new HashMap<>());Add an item to the inner HashMap:
inventory.get("Electronics").put("Laptop", 1200);Check if the outer map is empty and get its size:
System.out.println(inventory.isEmpty()); // false
System.out.println(inventory.size()); // 1Try it yourself
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static void printNestedInventory(HashMap<String, HashMap<String, Integer>> inventory) {
// Iterate over each category in the outer HashMap
// For each category, print "Category: <name>"
// If the inner map is empty, print " (No products)"
// Otherwise, iterate over each product and print " Product: <name>, Price: <price>"
// Write your code here
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String inventoryString = scanner.nextLine();
// Convert JSON string to Nested HashMap
Type inventoryType = new TypeToken<HashMap<String, HashMap<String, Integer>>>(){}.getType();
HashMap<String, HashMap<String, Integer>> inventory = new Gson().fromJson(inventoryString, inventoryType);
printNestedInventory(inventory);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays2HashMap Part 1
What is a HashMap?Declare a HashMapAccessing ValuesCheck If Key ExistsModifying DictionariesRecap - HashMap3HashMap Part 2
HashMap MethodsIterate with keySet()Iterate with entrySet()Nested HashMapRecap - Manage WarehouseRecap - HashMap Operations6Advanced Control Flow
Label StatementsSwitch ExpressionPattern MatchingGuard ClausesRecap - Control Flow