Java HashMap

Java HashMap is a class in the Java Collections Framework that is used to store key-value pairs. It is a type of associative array, which allows you to retrieve values based on their associated keys.

Here are some key features of Java HashMap:

  • It uses a hash table to store key-value pairs, which allows for fast retrieval of values based on their keys.
  • Keys must be unique, but values can be duplicated.
  • HashMap is not synchronized by default, but you can create a synchronized version of it using the Collections.synchronizedMap() method.
  • It does not maintain any order of the elements, so iteration order may vary.
  • Null values and keys are allowed, but only one null key is permitted.

Here is an example of how to use Java HashMap:

import java.util.HashMap;

public class HashMapExample {
  public static void main(String[] args) {
    // Create a new HashMap
    HashMap<String, Integer> scores = new HashMap<>();

    // Add some key-value pairs
    scores.put("John", 85);
    scores.put("Mary", 92);
    scores.put("Tom", 76);

    // Retrieve a value based on a key
    int johnsScore = scores.get("John");
    System.out.println("John's score: " + johnsScore);

    // Remove a key-value pair
    scores.remove("Tom");

    // Iterate through the keys and values
    for (String name : scores.keySet()) {
      int score = scores.get(name);
      System.out.println(name + ": " + score);
    }
  }
}

In this example, we create a new HashMap called scores, which stores names (keys) and scores (values) as String and Integer types, respectively. We add some key-value pairs using the put() method, retrieve John’s score using the get() method, remove Tom’s score using the remove() method, and iterate through the remaining key-value pairs using a for loop.

Hierarchy of HashMap class:

HashMap is a part of the Java Collections Framework and extends the AbstractMap class. It implements the Map interface, which provides a set of methods for working with key-value pairs. Here is the hierarchy of the HashMap class:

java.lang.Object
    java.util.AbstractMap
        java.util.HashMap

AbstractMap is an abstract class that provides a skeletal implementation of the Map interface. It defines some common methods and provides default implementations for certain methods. HashMap extends AbstractMap and provides a concrete implementation of the Map interface using a hash table.

In addition to the HashMap class, there are several other classes that are related to it:

  • LinkedHashMap: A subclass of HashMap that maintains a linked list of the entries in the map, which preserves the order of iteration.
  • TreeMap: A class that implements the NavigableMap interface and stores its entries in a sorted tree structure.
  • ConcurrentHashMap: A class that provides a high-performance concurrent implementation of the Map interface.
  • WeakHashMap: A class that uses weak references to keys, which allows unused entries to be removed automatically by the garbage collector.

All of these classes implement the Map interface, which means that they provide a similar set of methods for working with key-value pairs. However, they differ in their internal data structures and performance characteristics.

HashMap class declaration:

The declaration for the HashMap class in Java is as follows:

public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {
    
    // Class implementation
}

Here, K and V are type parameters that represent the key and value types, respectively. The HashMap class extends the AbstractMap class and implements the Map interface, as well as two additional interfaces, Cloneable and Serializable.

The AbstractMap class provides a skeletal implementation of the Map interface, which means that it defines some common methods and provides default implementations for certain methods. The Map interface itself defines the basic operations that can be performed on a map, such as put(), get(), remove(), containsKey(), and containsValue().

In addition to the methods inherited from AbstractMap and Map, the HashMap class also defines its own methods for working with key-value pairs. Some of the most commonly used methods of the HashMap class include:

  • put(K key, V value): Adds a key-value pair to the map.
  • get(Object key): Retrieves the value associated with a given key.
  • remove(Object key): Removes a key-value pair from the map.
  • containsKey(Object key): Checks if the map contains a given key.
  • containsValue(Object value): Checks if the map contains a given value.
  • size(): Returns the number of key-value pairs in the map.
  • isEmpty(): Returns true if the map is empty.
  • keySet(): Returns a set of all keys in the map.
  • values(): Returns a collection of all values in the map.
  • entrySet(): Returns a set of all key-value pairs in the map.

HashMap class Parameters:

The HashMap class in Java has two type parameters, K and V, which represent the types of keys and values that can be stored in the map. These type parameters are declared in the class declaration as follows:

public class HashMap<K,V> extends AbstractMap<K,V>

Here’s what these parameters mean:

  • K: The type of the keys that can be stored in the map. This can be any non-primitive reference type, including classes, interfaces, and arrays.
  • V: The type of the values that can be stored in the map. This can also be any non-primitive reference type.

When you create a HashMap object, you need to specify the types of the keys and values that you want to store in the map. For example:

HashMap<String, Integer> scores = new HashMap<>();

In this example, String is the key type, and Integer is the value type. This HashMap object can store key-value pairs where the keys are String objects and the values are Integer objects.

It’s important to note that the type parameters K and V are not limited to a specific set of types. You can use any non-primitive reference type as a key or value type. However, you should be careful when using mutable objects as keys, as changing a key’s state can affect the map’s behavior. Additionally, you should ensure that your key and value types implement the equals() and hashCode() methods correctly, as these methods are used by the HashMap class to determine equality and hash codes for keys.

Constructors of Java HashMap class:

The HashMap class in Java provides several constructors that allow you to create a new hash map object with different initial capacities and load factors. Here are the constructors of the HashMap class:

  1. HashMap(): Creates an empty hash map with the default initial capacity (16) and load factor (0.75).
  2. HashMap(int initialCapacity): Creates an empty hash map with the specified initial capacity and the default load factor (0.75).
  3. HashMap(int initialCapacity, float loadFactor): Creates an empty hash map with the specified initial capacity and load factor.
  4. HashMap(Map<? extends K, ? extends V> m): Creates a new hash map with the same key-value mappings as the specified map.

Here’s an explanation of each constructor:

  1. This constructor creates an empty hash map with the default initial capacity of 16 and the default load factor of 0.75. The initial capacity is the number of buckets in the hash table, and the load factor determines how full the hash table can be before it is resized. When the number of entries in the map exceeds the product of the load factor and the current capacity, the hash table is resized and the entries are rehashed.
  2. This constructor creates an empty hash map with the specified initial capacity and the default load factor of 0.75. The initial capacity should be a positive integer, and it determines the number of buckets in the hash table. If the specified initial capacity is negative, an IllegalArgumentException is thrown.
  3. This constructor creates an empty hash map with the specified initial capacity and load factor. The load factor should be a positive float value between 0 and 1, inclusive. If the specified load factor is not within this range, an IllegalArgumentException is thrown.
  4. This constructor creates a new hash map with the same key-value mappings as the specified map. The map is initialized with the default initial capacity (16) and load factor (0.75), and then the entries from the specified map are added to it. If the specified map is null, a NullPointerException is thrown.

Methods of Java HashMap class:

The HashMap class in Java provides a variety of methods to add, remove, and retrieve elements from the hash map. Here are some of the most commonly used methods:

  1. put(K key, V value): Associates the specified value with the specified key in the map. If the map previously contained a mapping for the key, the old value is replaced. Returns the previous value associated with the key, or null if there was no mapping for the key.
  2. get(Object key): Returns the value to which the specified key is mapped, or null if the map contains no mapping for the key.
  3. remove(Object key): Removes the mapping for the specified key from the map, if it is present. Returns the previous value associated with the key, or null if there was no mapping for the key.
  4. containsKey(Object key): Returns true if the map contains a mapping for the specified key.
  5. containsValue(Object value): Returns true if the map contains one or more mappings to the specified value.
  6. size(): Returns the number of key-value mappings in the map.
  7. isEmpty(): Returns true if the map contains no key-value mappings.
  8. clear(): Removes all key-value mappings from the map.
  9. keySet(): Returns a set of the keys contained in the map.
  10. values(): Returns a collection of the values contained in the map.
  11. entrySet(): Returns a set of the key-value mappings contained in the map.
  12. putAll(Map<? extends K, ? extends V> m): Copies all of the mappings from the specified map to the map.
  13. hashCode(): Returns the hash code value for the map.
  14. equals(Object obj): Returns true if the specified object is also a map and the two maps have the same key-value mappings.

These methods provide a basic set of functionality for working with HashMap objects in Java. Other methods, such as compute(), merge(), replaceAll(), and forEach(), are also available in the HashMap class for more advanced operations.

Java HashMap Example:

Here’s an example of how to use the HashMap class in Java:

import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        // Create a new HashMap object
        HashMap<String, Integer> map = new HashMap<>();

        // Add key-value mappings to the map
        map.put("Alice", 25);
        map.put("Bob", 30);
        map.put("Charlie", 35);
        map.put("Dave", 40);

        // Print the size of the map
        System.out.println("Size of map: " + map.size());

        // Print the value associated with a key
        System.out.println("Value for key Bob: " + map.get("Bob"));

        // Remove a key-value mapping from the map
        map.remove("Charlie");

        // Check if a key is present in the map
        if (map.containsKey("Dave")) {
            System.out.println("Dave is present in the map");
        }

        // Iterate over the key-value mappings in the map
        for (String key : map.keySet()) {
            int value = map.get(key);
            System.out.println(key + " = " + value);
        }
    }
}

This program creates a HashMap object that maps strings to integers. It adds several key-value mappings to the map, prints the size of the map, retrieves the value associated with a key, removes a key-value mapping from the map, checks if a key is present in the map, and iterates over the key-value mappings in the map, printing each one. The output of the program is:

Size of map: 4
Value for key Bob: 30
Dave is present in the map
Bob = 30
Alice = 25
Dave = 40

No Duplicate Key on HashMap:

In Java’s HashMap class, duplicate keys are not allowed. When a key-value pair is added to the map using the put() method and the key already exists in the map, the old value associated with that key is replaced by the new value. The map does not allow multiple values to be associated with the same key.

For example, if you have a HashMap<String, Integer> and you add the key-value pairs “Alice”=25 and “Alice”=30 to the map, the value associated with the key “Alice” will be 30, not 25. Here’s an example code snippet:

HashMap<String, Integer> map = new HashMap<>();
map.put("Alice", 25);
map.put("Alice", 30);
int aliceValue = map.get("Alice"); // aliceValue will be 30, not 25

If you need to store multiple values for the same key, you can use a data structure like a List or a Set as the value type in the HashMap. For example, you could use a HashMap<String, List<Integer>> to store a list of integers for each string key:

HashMap<String, List<Integer>> map = new HashMap<>();
List<Integer> aliceValues = new ArrayList<>();
aliceValues.add(25);
aliceValues.add(30);
map.put("Alice", aliceValues);
List<Integer> aliceValuesFromMap = map.get("Alice"); // aliceValuesFromMap will be [25, 30]

Java HashMap example to add() elements:

Sure, here’s an example of how to use the add() method to add elements to a HashMap in Java:

import java.util.HashMap;

public class HashMapAddExample {
    public static void main(String[] args) {
        // Create a new HashMap object
        HashMap<String, Integer> map = new HashMap<>();

        // Add key-value mappings to the map using the add() method
        map.computeIfAbsent("Alice", k -> 0).add(25);
        map.computeIfAbsent("Alice", k -> 0).add(30);
        map.computeIfAbsent("Bob", k -> 0).add(35);
        map.computeIfAbsent("Charlie", k -> 0).add(40);

        // Print the size of the map
        System.out.println("Size of map: " + map.size());

        // Print the values associated with a key
        System.out.println("Values for key Alice: " + map.get("Alice"));

        // Remove a key-value mapping from the map
        map.remove("Charlie");

        // Check if a key is present in the map
        if (map.containsKey("Bob")) {
            System.out.println("Bob is present in the map");
        }

        // Iterate over the key-value mappings in the map
        for (String key : map.keySet()) {
            List<Integer> values = map.get(key);
            System.out.println(key + " = " + values);
        }
    }
}

This program creates a HashMap object that maps strings to lists of integers. It uses the computeIfAbsent() method to add elements to the list associated with each key. This method retrieves the existing list associated with the key, or creates a new one if the key is not already in the map, and then adds the element to the list. The program also prints the size of the map, retrieves the list of values associated with a key, removes a key-value mapping from the map, checks if a key is present in the map, and iterates over the key-value mappings in the map, printing each one.

Java HashMap example to remove() elements:

Certainly, here’s an example of how to use the remove() method to remove elements from a HashMap in Java:

import java.util.HashMap;

public class HashMapRemoveExample {
    public static void main(String[] args) {
        // Create a new HashMap object
        HashMap<String, Integer> map = new HashMap<>();

        // Add key-value mappings to the map using the put() method
        map.put("Alice", 25);
        map.put("Bob", 30);
        map.put("Charlie", 35);

        // Print the size of the map
        System.out.println("Size of map: " + map.size());

        // Remove a key-value mapping from the map
        int removedValue = map.remove("Bob");

        // Print the removed value
        System.out.println("Removed value: " + removedValue);

        // Check if a key is present in the map
        if (map.containsKey("Charlie")) {
            System.out.println("Charlie is present in the map");
        }

        // Iterate over the key-value mappings in the map
        for (String key : map.keySet()) {
            int value = map.get(key);
            System.out.println(key + " = " + value);
        }
    }
}

This program creates a HashMap object that maps strings to integers. It adds key-value mappings to the map using the put() method, prints the size of the map, removes a key-value mapping from the map using the remove() method, prints the value that was removed, checks if a key is present in the map, and iterates over the key-value mappings in the map, printing each one.

Java HashMap example to replace() elements:

Sure, here’s an example of how to use the replace() method to replace elements in a HashMap in Java:

import java.util.HashMap;

public class HashMapReplaceExample {
    public static void main(String[] args) {
        // Create a new HashMap object
        HashMap<String, Integer> map = new HashMap<>();

        // Add key-value mappings to the map using the put() method
        map.put("Alice", 25);
        map.put("Bob", 30);
        map.put("Charlie", 35);

        // Print the size of the map
        System.out.println("Size of map: " + map.size());

        // Replace a value for a key in the map
        int oldValue = map.replace("Bob", 40);

        // Print the old and new values
        System.out.println("Old value: " + oldValue);
        System.out.println("New value: " + map.get("Bob"));

        // Check if a key is present in the map
        if (map.containsKey("Charlie")) {
            System.out.println("Charlie is present in the map");
        }

        // Iterate over the key-value mappings in the map
        for (String key : map.keySet()) {
            int value = map.get(key);
            System.out.println(key + " = " + value);
        }
    }
}

This program creates a HashMap object that maps strings to integers. It adds key-value mappings to the map using the put() method, prints the size of the map, replaces a value for a key in the map using the replace() method, prints the old and new values, checks if a key is present in the map, and iterates over the key-value mappings in the map, printing each one.

Difference between HashSet and HashMap:

HashSet and HashMap are both classes in Java that are used to store collections of objects. However, they have some key differences in their functionality:

  1. Data Structure: HashSet is an implementation of the Set interface, which means it stores a collection of unique objects, while HashMap is an implementation of the Map interface, which stores key-value pairs.
  2. Duplicates: HashSet does not allow duplicate elements, while HashMap allows duplicate values but not duplicate keys.
  3. Retrieval: In HashSet, elements are stored as individual objects, while in HashMap, elements are stored as key-value pairs. This means that in HashMap, you can retrieve a value by providing its corresponding key, while in HashSet, you can only check if a particular element is present or not.
  4. Iteration: HashSet provides a way to iterate over all its elements, but there is no order maintained. HashMap provides two ways to iterate: over the keys, or over the key-value pairs, and the order of iteration is not guaranteed.
  5. Performance: HashSet is generally faster than HashMap for simple operations like adding or checking for the presence of an element, since it only needs to check for uniqueness. However, HashMap provides faster access to specific elements, since it allows you to retrieve a value by its key.

In summary, HashSet is used to store a collection of unique elements, while HashMap is used to store key-value pairs. Both have their own advantages and disadvantages, and the choice between them depends on the specific use case.

Java HashMap Example: Book

Sure, here’s an example of how to use a HashMap in Java to store information about books:

import java.util.HashMap;

public class BookHashMapExample {
    public static void main(String[] args) {
        // Create a new HashMap object to store information about books
        HashMap<String, Book> bookMap = new HashMap<>();

        // Create some Book objects
        Book book1 = new Book("The Lord of the Rings", "J.R.R. Tolkien", 1954);
        Book book2 = new Book("To Kill a Mockingbird", "Harper Lee", 1960);
        Book book3 = new Book("Pride and Prejudice", "Jane Austen", 1813);

        // Add the books to the map
        bookMap.put("LOTR", book1);
        bookMap.put("TKAM", book2);
        bookMap.put("P&P", book3);

        // Retrieve a book from the map by its key
        String key = "LOTR";
        Book book = bookMap.get(key);

        // Print the book's information
        System.out.println("Key: " + key);
        System.out.println("Title: " + book.getTitle());
        System.out.println("Author: " + book.getAuthor());
        System.out.println("Year: " + book.getYear());
    }
}

class Book {
    private String title;
    private String author;
    private int year;

    public Book(String title, String author, int year) {
        this.title = title;
        this.author = author;
        this.year = year;
    }

    public String getTitle() {
        return title;
    }

    public String getAuthor() {
        return author;
    }

    public int getYear() {
        return year;
    }
}

In this example, we create a HashMap object to store information about books, where the keys are strings that represent unique identifiers for the books, and the values are Book objects that store information about each book.

We then create some Book objects and add them to the map using the put() method. We retrieve a book from the map using its key and store it in a variable called book. We can then use the methods provided by the Book class to retrieve information about the book and print it to the console.