Compound Data Structures in Java

Compound Data Structures in Java

Welcome to our exploration of Compound Data Structures in Java. Having navigated through Maps, Sets, and Arrays, we'll delve into nested HashMaps and arrays. These structures enable us to handle complex and hierarchical data, which is typical in real-world scenarios. Nested data structures are commonly used to represent data models like organizational charts, product categories, and multi-dimensional datasets. This lesson will guide you through a recap of the basics, as well as the creation and modification of nested HashMaps and arrays.

Recap: Maps, Arrays, and Understanding Nested Structures

As a quick recap, Arrays are mutable, ordered collections, while HashMaps are collections of key-value pairs with unique keys. These structures can be nested. Here's a simple example of a school directory:

import java.util.HashMap;

public class Solution {
    public static void main(String[] args) {
        // HashMap with grades as keys and arrays of students as values
        HashMap<String, String[]> schoolDirectory = new HashMap<>();
        schoolDirectory.put("Grade1", new String[] { "Amy", "Bobby", "Charlie" });
        schoolDirectory.put("Grade2", new String[] { "David", "Eve", "Frank" });
        schoolDirectory.put("Grade3", new String[] { "George", "Hannah", "Ivy" });

        // Logs the Grade1 array in the HashMap
        System.out.println(String.join(", ", schoolDirectory.get("Grade1"))); // Output: Amy, Bobby, Charlie
    }
}

In this example, we have a HashMap where each key represents a grade, and the corresponding value is an array of student names. This is a simple demonstration of a nested data structure.

Creating Nested HashMaps and Arrays

Just like their non-nested versions, creating nested structures is straightforward.

Nested HashMap:

import java.util.HashMap;
import java.util.Map;

public class Solution {
    public static void main(String[] args) {
        // HashMap within a HashMap
        HashMap<String, HashMap<String, String>> nestedMap = new HashMap<>();
        nestedMap.put("fruit", new HashMap<>() {{
            put("apple", "red");
            put("banana", "yellow");
        }});
        nestedMap.put("vegetable", new HashMap<>() {{
            put("carrot", "orange");
            put("spinach", "green");
        }});

        // Logs the nested map
        for (Map.Entry<String, HashMap<String, String>> category : nestedMap.entrySet()) {
            System.out.println(category.getKey() + ":");
            for (Map.Entry<String, String> item : category.getValue().entrySet()) {
                System.out.println("  " + item.getKey() + ": " + item.getValue());
            }
        }
    }
}

Here, we have a HashMap that contains other HashMaps as values. Each top-level key, such as "fruit" or "vegetable," points to another HashMap that holds key-value pairs related to that top-level category.

We utilize double-brace initialization to populate these nested HashMaps efficiently. This technique involves creating an anonymous inner subclass of HashMap (first brace: new HashMap<>() { ... }) and using an instance initializer block (second brace: { ... }) to add key-value pairs like put("apple", "red") immediately at runtime, in one step.

Nested Array:

import java.util.Arrays;

public class Solution {
    public static void main(String[] args) {
        // Arrays within an array
        int[][] nestedArray = {
            { 1, 2, 3 },
            { 4, 5, 6 },
            { 7, 8, 9 }
        };

        // Logs the nested array
        for (int[] innerArray : nestedArray) {
            System.out.println(Arrays.toString(innerArray));
        }
    }
}

In this case, we create a nested array where each element of the outer array is itself an array. This structure is useful for scenarios like multi-dimensional datasets.

Nested HashMaps and Arrays:

import java.util.HashMap;
import java.util.Map;
import java.util.Arrays;

public class Solution {
    public static void main(String[] args) {
        // Arrays within a HashMap
        HashMap<String, int[]> arrayMap = new HashMap<>();
        arrayMap.put("numbers", new int[] { 1, 2, 3 });
        arrayMap.put("letters", new int[] { 10, 11, 12 });

        // Logs the HashMap of arrays
        for (Map.Entry<String, int[]> pair : arrayMap.entrySet()) {
            System.out.println(pair.getKey() + ": " + Arrays.toString(pair.getValue()));
        }
    }
}

This example shows a HashMap where each value is an array. This pattern is practical for mapping categories to lists of values efficiently.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal