Advanced Map Structures
Maps can contain complex data types, including lists as values. This allows you to create sophisticated data structures for real-world applications.Maps with List Values
You can create maps where each key maps to a list of values:The syntax
Map<String, List<int>> means each key (String) maps to a list of integers. This is perfect for storing multiple values per category.Real-World Example: Grade Management System
Let’s build a complete grade management system that:- Calculates the average for each subject
- Finds the best and worst performing subjects
- Generates a comprehensive report
Calculating Subject Averages
Finding the Best Subject
Finding the Worst Subject
We initialize
peorPromedio to 100.0 (the maximum possible grade) to ensure any actual grade will be lower.Generating Reports
Complete Working Example
Complex Map Structures
Common Patterns with Complex Maps
Pattern 1: Aggregate Data
Calculate statistics from lists in maps:Pattern 2: Find Extremes
Find maximum or minimum values:Pattern 3: Transform Data
Convert one map structure to another:Pattern 4: Filter and Report
Generate reports based on conditions:Real-World Applications
Student Records
Track multiple grades per subject for each student
Sales Data
Store daily sales figures for each product or region
Inventory Management
Track multiple warehouses with stock levels per item
Analytics
Collect and analyze time-series data by category
Advanced Techniques
Using reduce() for Calculations
Sorting Map Entries
Creating Maps from Lists
Performance Considerations
Best Practices
- Separate concerns: Create different maps for raw data vs. calculated results
- Validate data: Check for empty lists before calculating averages
- Use meaningful names: Choose clear variable names like
calificacionesPorMateria - Format output: Use
toStringAsFixed()for consistent number formatting - Modular functions: Break complex operations into smaller, reusable functions
Error Handling
Always check if lists are empty before performing calculations to avoid division by zero or other errors.