The Collection family
Know the four shapes of data the JDK gives you and how they relate to each other.
Open this lesson in the learning hubKey points
- Three questions decide everything: do duplicates matter, does order matter, do you look things up by key?
Listkeeps order, allows duplicates.Setrejects duplicates.Dequeadds both ends.Mapis not aCollection. It stores key-value pairs, so it sits beside the hierarchy, not inside it.- A Map still exposes collection views:
keySet(),values()andentrySet(). - Declare the interface, assign the class:
List<String> x = new ArrayList<>(). Swaps then cost one word.
Example
import java.util.*;
public class Main {
public static void main(String[] args) {
Collection<String> list = new ArrayList<>(List.of("a", "b", "a"));
Collection<String> set = new LinkedHashSet<>(list);
Map<String, Integer> map = new LinkedHashMap<>();
for (String s : list) map.merge(s, 1, Integer::sum);
System.out.println("List (ordered, duplicates ok) : " + list);
System.out.println("Set (no duplicates) : " + set);
System.out.println("Map (key -> value) : " + map);
System.out.println();
System.out.println("list is a Collection ? " + (list instanceof Collection));
System.out.println("map is a Collection ? " + (map instanceof Collection));
System.out.println("map.keySet() is a Set : " + map.keySet());
System.out.println("map.values() is a Collection : " + map.values());
}
}
Pick the interface that matches your data, not the class that feels familiar.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Collections course, and every lesson in it is listed on the Collections contents page.