Key Concepts

Directions: Fill in the blanks, this is a Popcorn HACK

Hashing

  • HashMap uses a hash function to map keys to their respective buckets.
    • Bucket: type of data structure
  • A good hash function generates a unique hash code for each key, but collisions can still occur.
  • The hash map in Java does not maintain insertion order.

Performance

  • HashMap provides constant-time performance (O(1)) for get() and put() operations.
  • Performance can degrade to O(n) in the worst case, especially if there are many hash collisions.
    • non-unique keys, only when allowed

actual: will be constant but not always 1

Key and Value Types

  • HashMap allows any non-null object as a key and any object (including null) as a value.
  • For a class to be used as a key, it must implement the equals and hash code methods.

Iteration:

  • HashMap provides methods like keySet(), values(), and entrySet() for iterating over key-value pairs.
  • The entrySet() method returns a Set view of key-value pairs, allowing for iteration and modification.

Thread Safety

  • HashMap is not thread-safe. For thread-safe operations, use ConcurrentHashMap.

What is HashMap

A HashMap store items in “key/value” pairs, and you can access them by an index of another type (e.g. a String).

One object is used as a key (index) to another object (value). It can store different types: String keys and Integer values, or the same type, like: String keys and String values:

Creating HashMap in Java

import java.util.HashMap; // import the HashMap class

public class CreateHashMap{
    public static void main(String[] args){
        // Generating the HashMap
    HashMap<String, String> capitalCities = new HashMap<String, String>();
    // Adding key/value pairs tothe HashMap to store
            capitalCities.put("America", "D.C");
            capitalCities.put("Germany", "Berlin");
            capitalCities.put("United Kingdom", "London");
            capitalCities.put("India", "Delhi");
            capitalCities.put("Afghanistan", "Delhi");
            capitalCities.put("Bangladesh", "Dhaka");
            
            System.out.println("Successfully created a HashMap which stores items in key/value pairs");
    }
}

CreateHashMap.main(null);


Successfully created a HashMap which stores items in key/value pairs

Methods in HashMap


import java.util.HashMap;
 
public class ExampleHashMap {
      public static void main(String[] args) {
       
      // Create a HashMap
      HashMap<String, Integer> hashMap = new HashMap<>();
       
      // Add elements to the HashMap
      hashMap.put("Shivansh", 25);
      hashMap.put("Shaurya", 30);
      hashMap.put("Patrick Mahomes", 28);
      hashMap.put("Travis Kelce", 34);
      hashMap.put("Tom Brady", 46);
       
      // HashMap put() method in Java (Access elements in the HashMap)
      System.out.println(hashMap.get("Shivansh")); 

      // HashMap remove() method in Java (Remove an element from the HashMap)
      hashMap.remove("Tom Brady");
       
      // HashMap size() method in Java (Get the size of the HashMap)
      System.out.println(hashMap.size()); 

      // HashMap entrySet() method in Java (Get the Entry Set)
      System.out.println("The set is: " + hashMap.entrySet()); 

      // HashMap containsKey() method in Java (check whether a particular key is being mapped into the HashMap or not)
      System.out.println("Is the key 'Shivansh' present? " + hashMap.containsKey("Shivansh"));
      
      
   }
}
ExampleHashMap.main(null);
25
4
The set is: [Travis Kelce=34, Shivansh=25, Shaurya=30, Patrick Mahomes=28]
Is the key 'Shivansh' present? true

Popcorn Hack 1

Declare a Hashmap, and then research 5 different HashMap method which were not listed above and use them in your code just like the one above.

// Code Here
import java.util.HashMap;
 
public class SuperMap {
    public static void main(String[] args) {
        HashMap<String, Integer> testMap = new HashMap<>();

        // putAll() - puts all key/value pairs from one map into another
        testMap.putAll(hashMap);

        // putIfAbsent() - only puts a value if the key is not already there
        testMap.putIfAbsent("Shivansh", "This will not be added"); // Will not be added as the key is already in
        testMap.putIfAbsent("Aiden", "This will be added"); // Key not present, therefore this will be added

        // .values() - returns all the values
        testMap.values()

        // .replace() - replaces the value of a given key
        testMap.replace("Shivansh", "code code");

        // Not a new method just proving it changed
        testMap.get("Shivansh");
    }
}

Traversing through HashMap

In the code below, hash_map.entrySet() is used to return a set view of the mapped elements. Now, getValue() and getKey() functions, key-value pairs can be iterated.

import java.util.HashMap;
public class TraverseHashMap{
public static void main(String[] args){
   // Week 15 NFL Quarterback Rankings
   HashMap<Integer, String> hash_map = new HashMap<>();
   hash_map.put(1, "Jalen Hurts");
   hash_map.put(2, "Dak Prescott");
   hash_map.put(3, "Josh Allen");
   hash_map.put(4, "Lamar Jackson");
   hash_map.put(5, "Brock Purdy");
    for (Map.Entry<Integer, String> set : hash_map.entrySet()) {
        System.out.println(set.getKey() + " = " + set.getValue());
    }
}
}
TraverseHashMap.main(null);


1 = Jalen Hurts
2 = Dak Prescott
3 = Josh Allen
4 = Lamar Jackson
5 = Brock Purdy

Popcorn Hack 2 (Extra Credit)

Try to find a different way to traverse a HashMap (Hint: try using a forEach function)

// Code Here
import java.util.HashMap;
public class TraverseHashMap{
public static void main(String[] args){
   // Week 15 NFL Quarterback Rankings
   HashMap<Integer, String> hash_map = new HashMap<>();
   hash_map.put(1, "Jalen Hurts");
   hash_map.put(2, "Dak Prescott");
   hash_map.put(3, "Josh Allen");
   hash_map.put(4, "Lamar Jackson");
   hash_map.put(5, "Brock Purdy");

   hash_map.forEach((key, value) -> System.out.println(key + " = " + value));
}
}
TraverseHashMap.main(null);


1 = Jalen Hurts
2 = Dak Prescott
3 = Josh Allen
4 = Lamar Jackson
5 = Brock Purdy

HashMaps in Java - Pet Registry Example

public class Pet {
    private final String name;
    private final int age;
    private final String color;

    public Pet(String name, int age, String color) {
        this.name = name;
        this.age = age;
        this.color = color;
    }

    public String getName() {
        return this.name;
    }

    public int getAge() {
        return this.age;
    }

    public String getColor() {
        return this.color;
    }
}

public class PetsRegistry {
    
    private HashMap<String, Pet> petRegistry = new HashMap<>(); // declares a private HashMap instance variable petRegistry
    // Key Type String and Value Type Pet

    public PetsRegistry() {
        // Add some pets to the registry
        petRegistry.put("Leo", new Pet("Lion", 8, "Gold"));
        petRegistry.put("Porky", new Pet("Pig", 3, "Pink"));
        petRegistry.put("Ro-Ro", new Pet("Robin", 7, "Red"));
        petRegistry.put("Midnight", new Pet("Cat", 10, "Black"));
        petRegistry.put("Hobbes", new Pet("Kitty", 1, "Calico"));
        petRegistry.put("Duke", new Pet("Dog", 14, "Brown"));
    }

    public Pet removePet(String name) {
        // Remove a pet by name
        return petRegistry.remove(name);
    }

    public void printRegistry() {
        // Iterate over the registry and print pet information
        for (String name : petRegistry.keySet()) { // for each loop
            Pet pet = petRegistry.get(name);
            System.out.println(name + " is a " + pet.getColor() + " " + pet.getName() +
                    " and is " + pet.getAge() + " years old.");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        // Initialize the pet registry
        PetsRegistry petsRegistry = new PetsRegistry();
        petsRegistry.printRegistry();

        // Remove a pet
        String petNameToRemove = "Hobbes";
        Pet removedPet = petsRegistry.removePet(petNameToRemove);
        if (removedPet == null) {
            System.out.println(petNameToRemove + " not found");
        } else {
            System.out.println("Removed: " + petNameToRemove + ", " + removedPet);
        }

        // Print the updated registry
        petsRegistry.printRegistry();
    }
}
PetsRegistry.main(null)
Hobbes is a Calico Kitty and is 1 years old.
Leo is a Gold Lion and is 8 years old.
Porky is a Pink Pig and is 3 years old.
Ro-Ro is a Red Robin and is 7 years old.
Duke is a Brown Dog and is 14 years old.
Midnight is a Black Cat and is 10 years old.

Removed: Hobbes, REPL.$JShell$24$Pet@4a5e5067
Leo is a Gold Lion and is 8 years old.
Porky is a Pink Pig and is 3 years old.
Ro-Ro is a Red Robin and is 7 years old.
Duke is a Brown Dog and is 14 years old.
Midnight is a Black Cat and is 10 years old.

Popcorn HACK 3 (Shaurya)

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

public class HashMapTest {
    public static void main(String[] args) {
        // Create a new HashMap with Integer keys and String values
        Map<Integer, String> myMap = new HashMap<>();

        // Add some key-value pairs to the HashMap
        myMap.put(1, "Apple");
        myMap.put(2, "Banana");
        myMap.put(3, "Cherry");

        // Fill in the blanks: Retrieve and print the value for key 2
        String valueForKey2 = myMap.get(2);
        System.out.println("Value for key 2: " + valueForKey2);

        // Fill in the blanks: Check if the HashMap contains key 4
        boolean containsKey4 = myMap.containsKey(4);
        System.out.println("Does the map contain key 4? " + containsKey4);

        // Fill in the blanks: Remove the entry with key 1 from the HashMap
        myMap.remove(1);

        // Print the updated contents of the HashMap
        System.out.println("Updated HashMap:");
        for (Map.Entry<Integer, String> entry : myMap.entrySet()) {
            System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
        }
    }
}

Popcorn HACK 4 - Quiz (Shaurya)

Multiple Choice:

Question 1: Hashing in HashMap

What is the primary purpose of a hash function in a HashMap?

  • A) To encrypt the keys
  • B) To map keys to corresponding buckets
  • C) To validate the keys
  • D) To generate random numbers

B

Question 2: Performance of HashMap

What is the time complexity of the get() and put() operations in a well-distributed HashMap?

  • A) O(log n)
  • B) O(n)
  • C) O(1)
  • D) O(n^2)

C, It should be O(c) but close enough

Free Response:

Question 3: Key and Value Types in HashMap

Describe the types of objects that can be used as keys and values in a HashMap. Additionally, explain the methods that a class should implement if used as a key.

Non-null objects can be used as keys, and any object can be used as a value. In order to be a key, the object must have the equals and hash code methods.

Question 4: Iteration in HashMap

Provide brief explanations for two methods in HashMap that can be used to iterate over its key-value pairs.

forEach() iterates through each key value pair and can be used to perform tasks on the pairs. you can use get() with a for loop to iterate (self-explanatory)

Question 5: Thread Safety in HashMap

Explain why HashMap is not thread-safe and what issues might arise when multiple threads access the same HashMap instance concurrently. Suggest an alternative class that can be used for concurrent access and explain its benefits.

Brother you could not even answer this question. Alternative is concurrent hashmap but this question shouldn’t count anyways.

HACKS (Shaurya)

1) Finish Popcorn HACKS 2) Develop a Java application that utilizes a HashMap to manage a sports team roster. Each player on the team should have attributes like name, position, and jersey number. The program should enable functionalities such as adding new players, updating player information, and searching for players based on their jersey numbers using the HashMap implementation. 3) Reflection (4-5 sentences)

MY HACKS

Sports roster

Below this cell

Reflection

So basically hashmaps are the exact same thing as dictionaries in Python, just made needlessly more complicated. I hate this language. I don’t like backend. I feel like a reflection on this was completely unnecessary and a waste of time.

import java.util.HashMap;

public class Player {
    public int id;
    public String pos;

    public Player(int id, String pos) {
        this.id = id;
        this.pos = pos;
    }
}

public class Roster {
    HashMap<String, Player> roster = new HashMap<>();

    public void add(String name, int id, String pos) {
        roster.put(name, new Player(id, pos));
    }

    public void remove(String name) {
        roster.remove(name);
    }

    public void replaceId(String name, int newId) {
        roster.get(name).id = newId;
    }

    public void replacePos(String name, String newPos) {
        roster.get(name).pos = newPos;
    }

    public void display(String name) {
        Player test = roster.get(name);

        System.out.println("\nPlayer data for " + name + ":");
        System.out.println("- name" + ": " + name);
        System.out.println("- id" + ": " + test.id);
        System.out.println("- position" + ": " + test.pos);
    }

    public void displayAll() {
        roster.forEach((key, value) -> this.display(key));
    }

    public static void main(String[] args) {
        Roster team = new Roster();

        // Add things!
        team.add("aiden", 1, "scrum master");
        team.add("toby", 2, "devops");
        team.add("ishi", 1000, "frontend dev");


        // Display individual item
        System.out.println("\nIndividual Item:");
        team.display("aiden");

        // Display all
        System.out.println("\nAll items:");
        team.displayAll();

        // Update attributes
        team.replaceId("aiden", 7000);
        team.replacePos("aiden", "product owner");

        // proof that updated
        System.out.println("\nUpdated Item:");
        team.display("aiden");

        // Remove items
        team.remove("toby");

        // Proof that item was removed
        System.out.println("\nAll items:");
        team.displayAll();
    }
}

Roster.main(null);
Individual Item:

Player data for aiden:
- name: aiden
- id: 1
- position: scrum master

All items:

Player data for toby:
- name: toby
- id: 2
- position: devops

Player data for ishi:
- name: ishi
- id: 1000
- position: frontend dev

Player data for aiden:
- name: aiden
- id: 1
- position: scrum master

Updated Item:

Player data for aiden:
- name: aiden
- id: 7000
- position: product owner

All items:

Player data for ishi:
- name: ishi
- id: 1000
- position: frontend dev

Player data for aiden:
- name: aiden
- id: 7000
- position: product owner