Summary - Collections
- Java course
- Beginner
- Lesson 70/116
- 5 min
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
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
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
import java.util.____;
import java.util.HashMap;
Explanation: java.util.HashMap is imported.