Hash Map Implementation

Simple hash map implementation with collision handling using chaining

By Cojocaru David1d ago (Sep 13, 2025)
tutorial
go
algorithms

Hash Map Implementation

go
package main

import (
    "fmt"
    "hash/fnv"
)

type HashNode struct {
    key   string
    value interface{}
    next  *HashNode
}

type HashMap struct {
    buckets []*HashNode
    size    int
}

func NewHashMap(size int) *HashMap {
    return &HashMap{
        buckets: make([]*HashNode, size),
        size:    size,
    }
}

func (hm *HashMap) hash(key string) int {
    h := fnv.New32a()
    h.Write([]byte(key))
    return int(h.Sum32()) % hm.size
}

func (hm *HashMap) Put(key string, value interface{}) {
    index := hm.hash(key)
    
    if hm.buckets[index] == nil {
        hm.buckets[index] = &HashNode{key: key, value: value}
        return
    }
    
    current := hm.buckets[index]
    for current != nil {
        if current.key == key {
            current.value = value
            return
        }
        if current.next == nil {
            break
        }
        current = current.next
    }
    
    current.next = &HashNode{key: key, value: value}
}

func (hm *HashMap) Get(key string) (interface{}, bool) {
    index := hm.hash(key)
    current := hm.buckets[index]
    
    for current != nil {
        if current.key == key {
            return current.value, true
        }
        current = current.next
    }
    
    return nil, false
}

func main() {
    hashMap := NewHashMap(10)
    
    hashMap.Put("name", "John")
    hashMap.Put("age", 30)
    hashMap.Put("city", "New York")
    
    if value, exists := hashMap.Get("name"); exists {
        fmt.Printf("Name: %v\n", value)
    }
}

Views

45

Lines

79

Characters

1,526

Likes

0

Details

Language
Go
Created
Sep 13, 2025
Updated
1d ago
Size
1.5 KB

Build your snippet library

Join thousands of developers organizing and sharing code snippets.