Summary - Generic collections
- Java course
- Intermediate
- Lesson 93/116
- 5 min
Combine List, Map and Set to write a word frequency counter.
Summary - Generic collections
This group covered four core collection interfaces: List ordered, Map key-value, Set unique, Queue/Deque FIFO and double-ended. Each has concrete implementations: ArrayList, HashMap, HashSet, ArrayDeque.
The Collections class provides helpers like sort, reverse, max and min. Type parameters (<E>, <K,V>) give compile-time type safety; adding the wrong type is a compile error.
Practice Build a score board
Combine three collections. Declare List<Integer> scores = new ArrayList<>();, add 70, 85, 70, 90 (70 is duplicated). Build Set<Integer> unique = new HashSet<>(scores); to drop duplicates. Print the list size with System.out.println(scores.size()); and the unique count with System.out.println(unique.size());.
Starter code
import java.util.List;
import java.util.ArrayList;
import java.util.Set;
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
// Declare List<Integer>, add 70,85,70,90; build Set to dedupe; print two sizes
}
}Sample solution
import java.util.List;
import java.util.ArrayList;
import java.util.Set;
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
List<Integer> scores = new ArrayList<>();
scores.add(70);
scores.add(85);
scores.add(70);
scores.add(90);
Set<Integer> unique = new HashSet<>(scores);
System.out.println(scores.size());
System.out.println(unique.size());
}
}Expected output
4 3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which collection rejects duplicate elements?
- List
- ArrayList
- Set Correct answer
- Queue
Explanation: Set holds unique elements; a duplicate add returns false.
2 Match interface to implementation
| Term | Meaning |
|---|---|
List |
ArrayList |
Map |
HashMap |
Set |
HashSet |
Queue |
ArrayDeque |
3 Match collection traits
| Term | Meaning |
|---|---|
List |
Ordered, allows duplicates |
Map |
Key-value pairs |
Set |
Unique elements |
Queue |
FIFO order |