CodeBlanks Logo Icon CodeBlanks

Summary - Collections

Combine ArrayList, HashMap and HashSet to write a phone book.

Summary: Collections

In this group you met three core collections: ArrayList (ordered list), HashMap (key-value), and HashSet (unique set).

They all live in the java.util package and provide type safety with generics. They are managed through common methods like add, get, put, contains and size.

Now you will combine the three to write a small phone book: names in an ArrayList, numbers in a HashMap, and tags in a HashSet.

Practice Phone book skeleton

Create a HashMap<String, String>; set "Ayşe" to "555-1000" and "Mehmet" to "555-2000". Then print the number of "Ayşe".

Starter code

Main.java
import java.util.HashMap;

public class Main {
  public static void main(String[] args) {
    // Create a HashMap<String, String> (name -> number)
    // Add Ayşe and Mehmet
    // Print Ayşe's number
  }
}

Sample solution

Main.java
HashMap<String, String> book = new HashMap<>();
book.put("Ayşe", "555-1000");
book.put("Mehmet", "555-2000");
System.out.println(book.get("Ayşe"));

Expected output

555-1000

Questions and answers

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

1 Which collection stores key-value pairs?

  • HashMap
  • HashSet
  • ArrayList Correct answer
  • int[]

Explanation: HashMap maps a key to a value.

2 Collection and typical use

Term Meaning
ArrayList Ordered element list
HashMap Key-value table
HashSet Unique tag set
int[] Fixed-length number array

3 Fill in the blank: import the collection

Question
import java.util.____;
Answer
import java.util.HashMap;

Explanation: java.util.HashMap is imported.

All lessons in Beginner