Skip to main content

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

This function takes two maps: one for input (grades) and one for output (averages). This pattern keeps data organized and functions focused.

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

Use toStringAsFixed(2) to format decimal numbers to 2 decimal places for cleaner output.

Complete Working Example

Sample Output:

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

When working with large maps containing lists:
  • Avoid unnecessary iterations through all data
  • Cache calculated values instead of recalculating
  • Consider using separate maps for different views of the data
For better organization:
  • Separate data processing into small, focused functions
  • Use descriptive function names that explain what they do
  • Keep data structures and their transformations clear and documented

Best Practices

  1. Separate concerns: Create different maps for raw data vs. calculated results
  2. Validate data: Check for empty lists before calculating averages
  3. Use meaningful names: Choose clear variable names like calificacionesPorMateria
  4. Format output: Use toStringAsFixed() for consistent number formatting
  5. 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.