Nested Hash Map Examples in Java

06 May 2023 Balmiki Mandal 0 Core Java

Understanding Nested HashMaps in Java

A Nested HashMap is a Map (specifically, an implementation of the Map interface) whose elements are contained within another Map. It provides an efficient way to store multiple related data items within a map. In this article, we'll look at some examples of how to use nested HashMaps in Java.

Creating a Nested HashMap

Creating a Nested HashMap is fairly straightforward. First, create a Map to hold the entries (e.g. a HashMap). Then, add key-value pairs to the Map, where the value is a second Map. Here’s an example:

Map<String, Map<String, Integer>> nestedHashMap = new HashMap<>();

Map<String, Integer> innerMap = new HashMap<>();
innerMap.put("one", 1);
innerMap.put("two", 2);
innerMap.put("three", 3);

nestedHashMap.put("Numbers", innerMap);

In this example, we’ve created a Map nestedHashMap with a single entry for “Numbers”. Its value is a second Map that contains key-value pairs for the numbers 1, 2, and 3.

Accessing a Nested HashMap

Once you’ve created a Nested HashMap, you can access it using the same methods that you would use to access a normal HashMap. To retrieve a specific element from the nested structure, use the get() method. For example, to retrieve the value associated with the key “one” from the inner Map, we could use the following code:

Integer one = nestedHashMap.get("Numbers").get("one");

The result would be the value 1.

Iterating Over a Nested HashMap

You can also iterate over a Nested HashMap using the standard iterator() method. Here’s an example of looping through all of the elements in the Nested HashMap created in the previous example:

Iterator<Entry<String, Map<String, Integer>>> outerIterator = nestedHashMap.entrySet().iterator();

while (outerIterator.hasNext()) {
    Entry<String, Map<String, Integer>> outerEntry = outerIterator.next();

    Iterator<Entry<String, Integer>> innerIterator = outerEntry.getValue().entrySet().iterator();

    while (innerIterator.hasNext()) {
        Entry<String, Integer> innerEntry = innerIterator.next();

        System.out.println(innerEntry.getKey() + ":" + innerEntry.getValue());
    }
}

The output of the above code would be:

one:1
two:2
three:3

Conclusion

In this article, we looked at some examples of working with Nested HashMaps in Java. We saw how to create a Nested HashMap, as well as how to access and iterate over the elements in the Map. With these techniques, you should have no trouble working with nested structures in Java.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.