Arrays as HashMaps Explained | Generated by AI

Home 2025.10

Yes, you’re absolutely right! Let me break it down clearly to confirm and expand on your thinking.

1. Arrays as a Simple Form of HashMap

2. Converting Arrays of Structs/Objects to HashMaps

Example in JavaScript (using reduce to build the map):

   const arrayOfObjects = [
     { id: 1, name: "Alice", age: 30 },
     { id: 2, name: "Bob", age: 25 },
     { id: 3, name: "Charlie", age: 35 }
   ];

   // Convert to hashmap: key = 'id', value = entire object
   const hashmap = arrayOfObjects.reduce((map, obj) => {
     map[obj.id] = obj;  // id as key
     return map;
   }, {});

   console.log(hashmap);
   // Output: {1: {id:1, name:'Alice', age:30}, 2: {id:2, name:'Bob', age:25}, 3: {id:3, name:'Charlie', age:35}}

   // Now lookup is fast: hashmap[1].name === "Alice"

Example in Python (using dict comprehension):

   array_of_objects = [
       {'id': 1, 'name': 'Alice', 'age': 30},
       {'id': 2, 'name': 'Bob', 'age': 25},
       {'id': 3, 'name': 'Charlie', 'age': 35}
   ]

   # Convert to dict: key = 'id', value = entire dict
   hashmap = {obj['id']: obj for obj in array_of_objects}

   print(hashmap)
   # Output: {1: {'id':1, 'name':'Alice', 'age':30}, 2: {'id':2, 'name':'Bob', 'age':25}, 3: {'id':3, 'name':'Charlie', 'age':35}}

   # Lookup: hashmap[1]['name'] == 'Alice'

Example in Java (using HashMap and streams):

   import java.util.*;
   import java.util.stream.Collectors;

   class Person {
       int id;
       String name;
       int age;
       // Constructor, getters, etc.
   }

   List<Person> arrayOfObjects = Arrays.asList(
       new Person(1, "Alice", 30),
       new Person(2, "Bob", 25),
       new Person(3, "Charlie", 35)
   );

   // Convert to HashMap: key = id, value = Person object
   Map<Integer, Person> hashmap = arrayOfObjects.stream()
       .collect(Collectors.toMap(Person::getId, person -> person));

   System.out.println(hashmap.get(1).getName());  // "Alice"

When/Why Do This Conversion?

If you’re working in a specific language or have a code example you’re trying to convert, share more details for tailored help! 😊


Back

x-ai/grok-4-fast

Donate