CodeBlanks Logo Icon CodeBlanks

put and get

Learn map operations with put() and get().

Map operations: put and get

You use put to add a pair to a HashMap and get to read a value by key. get returns null if the key is missing.

HashMap<String, Integer> stock = new HashMap<>();
stock.put("Kalem", 12);
stock.put("Defter", 5);
int n = stock.get("Kalem");
// n = 12

You can check whether a key exists with containsKey. This is safer when null is a possible value.

Safe lookup with containsKey

To check whether a key exists in the map, use containsKey. This is a lifesaver when you need to distinguish a missing key from an actual null value that get might return.

if (stock.containsKey("Silgi")) {
  int n = stock.get("Silgi");
  System.out.println(n);
} else {
  System.out.println("Not in stock");
}

Similarly, containsValue checks whether a value exists; but it is slower because the whole map must be scanned.

Practice Print the product stock

Print the value of the "Kalem" key in the given map; then check with containsKey whether "Silgi" exists, and print its value if so, or 0 otherwise.

Starter code

Main.java
import java.util.HashMap;

public class Main {
  public static void main(String[] args) {
    HashMap<String, Integer> stock = new HashMap<>();
    stock.put("Kalem", 12);
    // Print the value of Kalem
    // If Silgi exists print its value, otherwise print 0
  }
}

Sample solution

Main.java
System.out.println(stock.get("Kalem"));
if (stock.containsKey("Silgi")) {
  System.out.println(stock.get("Silgi"));
} else {
  System.out.println(0);
}

Expected output

12
0

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Fill in the blank: update the stock

Question
HashMap<String, Integer> stock = new HashMap<>();
stock.____("Kalem", 20);
Answer
HashMap<String, Integer> stock = new HashMap<>();
stock.put("Kalem", 20);

Explanation: put("Kalem", 20) updates the stock.

2 What does stock.get("Silgi") return when the key is missing?

  • It throws an error Correct answer
  • 0
  • An empty String
  • null

Explanation: A missing key returns null.

3 Match scenario to method

Term Meaning
Add or update a key put
Get the value of a key get
Does the key exist? containsKey
Does the value exist? containsValue

All lessons in Beginner