Intermediate level · Module 2: The Java Collections Framework · Lesson 1 of 3
Lists, Sets and Maps
Compare the main collection types and choose between them based on ordering, duplicates and lookup needs.
In this lesson you will
- Describe when to use List, Set and Map
- Use HashMap to count and group values
Key concepts
ListSetMapHashMap.merge / getOrDefault
The lesson
A List keeps items in order and allows duplicates; use it for sequences such as the sales of a day. A Set rejects duplicates; use it for things like the unique customers seen. A Map stores key–value pairs, such as product name to stock level, and finds a value by key quickly.
Declare variables by interface: List<String> names = new ArrayList<>(); Map<String, Integer> stock = new HashMap<>();. You can later switch to another implementation, such as LinkedHashMap to keep insertion order or TreeMap to keep keys sorted, without changing the rest of the code.
Counting is a common Map task: counts.merge(item, 1, Integer::sum) adds 1 to an item's count, starting at 1 if it is new. getOrDefault(key, 0) reads a value safely when the key may be missing.
Step by step
- Store a day's sold items in a List<String>.
- Put them in a Set to find the distinct items.
- Count each item with a Map<String, Integer> and merge.
- Switch the map to TreeMap and observe the sorted keys.
Practice activity
Count how many times each word appears in a short text and print the words alphabetically with their counts.
Expected result: The output lists each distinct word once, in alphabetical order, with the correct count.
Check your understanding
-
Which collection type rejects duplicates?
Show answer
Set.
-
Which Map implementation keeps its keys sorted?
Show answer
TreeMap.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.