Start learning free

LESSON 128 OF 671 · DICTIONARIES

Deleting a Key in Java

Lesson

TL ; DR:

A HashMap's remove method takes a key. It deletes that key and its value.


HashMap<String, Integer> toys = new HashMap<>();
toys.put("ball", 3);
toys.put("kite", 1);

toys.remove("kite");

System.out.println(toys.size());   // 1


Full lesson:

Sometimes an entry has to go. A shop stops selling an item. A player leaves the game.

Call remove on the map with the key. The key and its value go away together.

The size drops by 1. The key is gone, so toys.containsKey("kite") is now false.

remove also returns the value it deleted. For a missing key it returns null, and nothing changes.

Watch out: on an ArrayList, remove(2) takes out the item at index 2. On a HashMap, remove always takes a key.


Your task

A pet shop counts what it has for sale in animals. Each key is a kind of animal. Its value is how many the shop has.

The last rabbit just went home with a family. Delete the key "rabbit" from animals.

Then print animals.size() again. The code at the bottom checks if any rabbits are left.

Expected output:

3
2
No rabbits left
STEP 1 OF 2
    Ctrl + Enter to check