Nested Generic Types
What you'll learn: How to use one generic type as a type argument inside another, such as List<Map<String, Integer>>.
Why Nest Generics?
Real-world programs often need complex data structures. You might want a list of maps, a map containing lists, or even deeper nesting. Java generics allow you to combine types safely without losing compile-time type information.
Think of it like Russian nesting dolls: the outer doll (the container) holds inner dolls (which are themselves containers), each clearly labeled with what's inside.
Syntax and Examples
A nested generic type places one parameterized type inside another's angle brackets:
// A map where each key is a String, and each value is a List of Integers
Map<String, List<Integer>> gradesPerStudent = new HashMap<>();
// A list of maps, where each map pairs Strings to Doubles
List<Map<String, Double>> listOfMaps = new ArrayList<>();
You can nest as deeply as needed, though readability suffers beyond two or three levels:
Map<String, Map<Integer, List<String>>> deeplyNested = new HashMap<>();
Working with Nested Types
When you retrieve values, the type system tracks the nesting:
Map<String, List<Integer>> scores = new HashMap<>();
scores.put("Alice", new ArrayList<>());
List<Integer> aliceScores = scores.get("Alice"); // Returns List<Integer>
aliceScores.add(95);
aliceScores.add(88);
The diamond operator simplifies instantiation on the right side, inferring types from the left.
Key Takeaway:
Nested generic types like Map<String, List<Integer>> let you safely compose complex data structures, with full compile-time type checking at every level of nesting.