# Maps

Java HashMap is a [hash table](https://en.wikipedia.org/wiki/Hash_table) based implementation of Java’s Map interface. A Map, as you might know, is a collection of key-value pairs. It maps keys to values.![Java HashMap in Collection Hierarchy](https://www.callicoder.com/assets/images/post/large/java-hashmap-hierarchy.jpg)

Following are few key points to note about HashMaps in Java -

* A HashMap cannot contain duplicate keys.
* Java HashMap allows `null` values and the `null` key.
* HashMap is an unordered collection. It does not guarantee any specific order of the elements.
* Java HashMap is not thread-safe. You must explicitly synchronize concurrent modifications to the HashMap.

### Creating a HashMap and Adding key-value pairs to it <a href="#creating-a-hashmap-and-adding-key-value-pairs-to-it" id="creating-a-hashmap-and-adding-key-value-pairs-to-it"></a>

The following example shows how to create a HashMap, and add new key-value pairs to it.

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

public class CreateHashMapExample {
    public static void main(String[] args) {
        // Creating a HashMap
        Map<String, Integer> numberMapping = new HashMap<>();

        // Adding key-value pairs to a HashMap
        numberMapping.put("One", 1);
        numberMapping.put("Two", 2);
        numberMapping.put("Three", 3);

        // Add a new key-value pair only if the key does not exist in the HashMap, or is mapped to `null`
        numberMapping.putIfAbsent("Four", 4);

        System.out.println(numberMapping);
    }
}
```

```
# Output
{One=1, Four=4, Two=2, Three=3}
```

### Accessing keys and modifying their associated value in a HashMap <a href="#accessing-keys-and-modifying-their-associated-value-in-a-hashmap" id="accessing-keys-and-modifying-their-associated-value-in-a-hashmap"></a>

The example below shows:

* How to check if a HashMap is empty | [`isEmpty()`](https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#isEmpty--)
* How to find the size of a HashMap | [`size()`](https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#size--])
* How to check if a given key exists in a HashMap | [`containsKey()`](https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#containsKey-java.lang.Object-)
* How to check if a given value exists in a HashMap | [`containsValue()`](https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#containsValue-java.lang.Object-)
* How to get the value associated with a given key in the HashMap | [`get()`](https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#get-java.lang.Object-)
* How to modify the value associated with a given key in the HashMap | [`put()`](https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#put-K-V-)

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

public class AccessKeysFromHashMapExample {
    public static void main(String[] args) {
        Map<String, String> userCityMapping = new HashMap<>();

        // Check if a HashMap is empty
        System.out.println("is userCityMapping empty? : " + userCityMapping.isEmpty());

        userCityMapping.put("John", "New York");
        userCityMapping.put("Rajeev", "Bengaluru");
        userCityMapping.put("Steve", "London");

        System.out.println("userCityMapping HashMap : " + userCityMapping);

        // Find the size of a HashMap
        System.out.println("We have the city information of " + userCityMapping.size() + " users");

        String userName = "Steve";
        // Check if a key exists in the HashMap
        if(userCityMapping.containsKey(userName)) {
            // Get the value assigned to a given key in the HashMap
            String city = userCityMapping.get(userName);
            System.out.println(userName + " lives in " + city);
        } else {
            System.out.println("City details not found for user " + userName);
        }

        // Check if a value exists in a HashMap
        if(userCityMapping.containsValue("New York")) {
            System.out.println("There is a user in the userCityMapping who lives in New York");
        } else {
            System.out.println("There is no user in the userCityMapping who lives in New York");
        }


        // Modify the value assigned to an existing key
        userCityMapping.put(userName, "California");
        System.out.println(userName + " moved to a new city " + userCityMapping.get(userName) + ", New userCityMapping : " + userCityMapping);

        // The get() method returns `null` if the specified key was not found in the HashMap
        System.out.println("Lisa's city : " + userCityMapping.get("Lisa"));
    }
}
```

```
# Output
is userCityMapping empty? : true
userCityMapping HashMap : {Steve=London, John=New York, Rajeev=Bengaluru}
We have the city information of 3 users
Steve lives in London
There is a user in the userCityMapping who lives in New York
Steve moved to a new city California, New userCityMapping : {Steve=California, John=New York, Rajeev=Bengaluru}
Lisa's city : null
```

### Removing keys from a HashMap <a href="#removing-keys-from-a-hashmap" id="removing-keys-from-a-hashmap"></a>

The following example shows how to :

* Remove a key from a HashMap | [remove(Object key)](https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#remove-java.lang.Object-)
* Remove a key from a HashMap only if it is associated with a given value | [remove(Object key, Object value)](https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#remove-java.lang.Object-java.lang.Object-)

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

public class RemoveKeysFromHashMapExample {
    public static void main(String[] args) {
        Map<String, String> husbandWifeMapping = new HashMap<>();
        husbandWifeMapping.put("Jack", "Marie");
        husbandWifeMapping.put("Chris", "Lisa");
        husbandWifeMapping.put("Steve", "Jennifer");

        System.out.println("Husband-Wife Mapping : " + husbandWifeMapping);

        // Remove a key from the HashMap
        // Ex - Unfortunately, Chris got divorced. Let's remove him from the mapping
        String husband = "Chris";
        String wife = husbandWifeMapping.remove(husband);

        System.out.println("Couple (" + husband + " => " + wife + ") got divorced");
        System.out.println("New Mapping : " + husbandWifeMapping);

        // Remove a key from the HashMap only if it is mapped to the given value
        // Ex - Divorce "Jack" only if He is married to "Linda"
        boolean isRemoved = husbandWifeMapping.remove("Jack", "Linda");
        System.out.println("Did Jack get removed from the mapping? : " + isRemoved);

        // remove() returns null if the mapping was not found for the supplied key
        wife = husbandWifeMapping.remove("David");
        if(wife == null) {
            System.out.println("Looks like David is not married to anyone");
        } else {
            System.out.println("Removed David and his wife from the mapping");
        }
    }
}
```

```
# Output
Husband-Wife Mapping : {Steve=Jennifer, Chris=Lisa, Jack=Marie}
Couple (Chris => Lisa) got divorced
New Mapping : {Steve=Jennifer, Jack=Marie}
Did Jack get removed from the mapping? : false
Looks like David is not married to anyone
```

### Obtaining the entrySet, keySet, and values from a HashMap <a href="#obtaining-the-entryset-keyset-and-values-from-a-hashmap" id="obtaining-the-entryset-keyset-and-values-from-a-hashmap"></a>

The `Map` interface provides methods to retrieve the set of entries (key-value pairs), the set of keys, and the collection of values.

The following example shows how to retrieve them from a HashMap -

```java
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class HashMapEntryKeySetValuesExample {
    public static void main(String[] args) {
        Map<String, String> countryISOCodeMapping = new HashMap<>();

        countryISOCodeMapping.put("India", "IN");
        countryISOCodeMapping.put("United States of America", "US");
        countryISOCodeMapping.put("Russia", "RU");
        countryISOCodeMapping.put("Japan", "JP");
        countryISOCodeMapping.put("China", "CN");

        // HashMap's entry set
        Set<Map.Entry<String, String>> countryISOCodeEntries = countryISOCodeMapping.entrySet();
        System.out.println("countryISOCode entries : " + countryISOCodeEntries);

        // HashMap's key set
        Set<String> countries = countryISOCodeMapping.keySet();
        System.out.println("countries : " + countries);

        // HashMap's values
        Collection<String> isoCodes = countryISOCodeMapping.values();
        System.out.println("isoCodes : " + isoCodes);
    }
}
```

```
# Output
countryISOCode entries : [United States of America=US, Japan=JP, China=CN, India=IN, Russia=RU]
countries : [United States of America, Japan, China, India, Russia]
isoCodes : [US, JP, CN, IN, RU]
```

### Iterating over a HashMap <a href="#iterating-over-a-hashmap" id="iterating-over-a-hashmap"></a>

The following example shows different ways of iterating over a HashMap -

1. Iterating over a HashMap using Java 8 [forEach](https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#forEach-java.util.function.BiConsumer-) and lambda expression.
2. Iterating over the HashMap’s entrySet using [iterator()](https://docs.oracle.com/javase/8/docs/api/java/util/Set.html#iterator--).
3. Iterating over the HashMap’s entrySet using Java 8 [forEach](https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html#forEach-java.util.function.Consumer-) and lambda expression.
4. Iterating over the HashMap’s entrySet using simple for-each loop.
5. Iterating over the HashMap’s keySet.

```java
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class IterateOverHashMap {
    public static void main(String[] args) {
        Map<String, Double> employeeSalary = new HashMap<>();
        employeeSalary.put("David", 76000.00);
        employeeSalary.put("John", 120000.00);
        employeeSalary.put("Mark", 95000.00);
        employeeSalary.put("Steven", 134000.00);

        System.out.println("=== Iterating over a HashMap using Java 8 forEach and lambda ===");
        employeeSalary.forEach((employee, salary) -> {
            System.out.println(employee + " => " + salary);
        });

        System.out.println("\n=== Iterating over the HashMap's entrySet using iterator() ===");
        Set<Map.Entry<String, Double>> employeeSalaryEntries = employeeSalary.entrySet();
        Iterator<Map.Entry<String, Double>> employeeSalaryIterator = employeeSalaryEntries.iterator();
        while (employeeSalaryIterator.hasNext()) {
            Map.Entry<String, Double> entry = employeeSalaryIterator.next();
            System.out.println(entry.getKey() + " => " + entry.getValue());
        }

        System.out.println("\n=== Iterating over the HashMap's entrySet using Java 8 forEach and lambda ===");
        employeeSalary.entrySet().forEach(entry -> {
            System.out.println(entry.getKey() + " => " + entry.getValue());
        });

        System.out.println("\n=== Iterating over the HashMap's entrySet using simple for-each loop ===");
        for(Map.Entry<String, Double> entry: employeeSalary.entrySet()) {
            System.out.println(entry.getKey() + " => " + entry.getValue());
        }

        System.out.println("\n=== Iterating over the HashMap's keySet ===");
        employeeSalary.keySet().forEach(employee -> {
            System.out.println(employee + " => " + employeeSalary.get(employee));
        });
    }
}
```

```
# Output
=== Iterating over a HashMap using Java 8 forEach and lambda ===
David => 76000.0
John => 120000.0
Mark => 95000.0
Steven => 134000.0

=== Iterating over the HashMap's entrySet using iterator() ===
David => 76000.0
John => 120000.0
Mark => 95000.0
Steven => 134000.0

=== Iterating over the HashMap's entrySet using Java 8 forEach and lambda ===
David => 76000.0
John => 120000.0
Mark => 95000.0
Steven => 134000.0

=== Iterating over the HashMap's entrySet using simple for-each loop ===
David => 76000.0
John => 120000.0
Mark => 95000.0
Steven => 134000.0

=== Iterating over the HashMap's keySet ===
David => 76000.0
John => 120000.0
Mark => 95000.0
Steven => 134000.0
```

### Java HashMap with User defined objects <a href="#java-hashmap-with-user-defined-objects" id="java-hashmap-with-user-defined-objects"></a>

Check out the following example to learn how to create and work with a HashMap of user defined objects.

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

class Employee {
    private Integer id;
    private String name;
    private String city;

    public Employee(Integer id, String name, String city) {
        this.id = id;
        this.name = name;
        this.city = city;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", city='" + city + '\'' +
                '}';
    }
}

public class HashMapUserDefinedObjectExample {
    public static void main(String[] args) {
        Map<Integer, Employee> employeesMap = new HashMap<>();

        employeesMap.put(1001, new Employee(1001, "Rajeev", "Bengaluru"));
        employeesMap.put(1002, new Employee(1002, "David", "New York"));
        employeesMap.put(1003, new Employee(1003, "Jack", "Paris"));

        System.out.println(employeesMap);
    }
}
```

```
# Output
{1001=Employee{name='Rajeev', city='Bengaluru'}, 1002=Employee{name='David', city='New York'}, 1003=Employee{name='Jack', city='Paris'}}
```

### Problems:

**1.** Write a Java program to associate the specified value with the specified key in a HashMap. [Go to the editor](https://www.w3resource.com/java-exercises/collection/index.php#editorr)\
[Click me to see the solution](https://www.w3resource.com/java-exercises/collection/java-collection-hash-map-exercise-1.php)

**2.** Write a Java program to count the number of key-value (size) mappings in a map. [Go to the editor](https://www.w3resource.com/java-exercises/collection/index.php#editorr)\
[Click me to see the solution](https://www.w3resource.com/java-exercises/collection/java-collection-hash-map-exercise-2.php)

**3.** Write a Java program to copy all of the mappings from the specified map to another map. [Go to the editor](https://www.w3resource.com/java-exercises/collection/index.php#editorr)\
[Click me to see the solution](https://www.w3resource.com/java-exercises/collection/java-collection-hash-map-exercise-3.php)

**4.** Write a Java program to remove all of the mappings from a map. [Go to the editor](https://www.w3resource.com/java-exercises/collection/index.php#editorr)\
[Click me to see the solution](https://www.w3resource.com/java-exercises/collection/java-collection-hash-map-exercise-4.php)

**5.** Write a Java program to check whether a map contains key-value mappings (empty) or not. [Go to the editor](https://www.w3resource.com/java-exercises/collection/index.php#editorr)\
[Click me to see the solution](https://www.w3resource.com/java-exercises/collection/java-collection-hash-map-exercise-5.php)

**6.** Write a Java program to get a shallow copy of a HashMap instance. [Go to the editor](https://www.w3resource.com/java-exercises/collection/index.php#editorr)\
[Click me to see the solution](https://www.w3resource.com/java-exercises/collection/java-collection-hash-map-exercise-6.php)

**7.** Write a Java program to test if a map contains a mapping for the specified key. [Go to the editor](https://www.w3resource.com/java-exercises/collection/index.php#editorr)\
[Click me to see the solution](https://www.w3resource.com/java-exercises/collection/java-collection-hash-map-exercise-7.php)

**8.** Write a Java program to test if a map contains a mapping for the specified value. [Go to the editor](https://www.w3resource.com/java-exercises/collection/index.php#editorr)\
[Click me to see the solution](https://www.w3resource.com/java-exercises/collection/java-collection-hash-map-exercise-8.php)

**9.** Write a Java program to create a set view of the mappings contained in a map. [Go to the editor](https://www.w3resource.com/java-exercises/collection/index.php#editorr)\
[Click me to see the solution](https://www.w3resource.com/java-exercises/collection/java-collection-hash-map-exercise-9.php)

**10.** Write a Java program to get the value of a specified key in a map. [Go to the editor](https://www.w3resource.com/java-exercises/collection/index.php#editorr)\
[Click me to see the solution](https://www.w3resource.com/java-exercises/collection/java-collection-hash-map-exercise-10.php)

**11.** Write a Java program to get a set view of the keys contained in this map. [Go to the editor](https://www.w3resource.com/java-exercises/collection/index.php#editorr)\
[Click me to see the solution](https://www.w3resource.com/java-exercises/collection/java-collection-hash-map-exercise-11.php)

**12.** Write a Java program to get a collection view of the values contained in this map. [Go to the editor](https://www.w3resource.com/java-exercises/collection/index.php#editorr)\
[Click me to see the solution](https://www.w3resource.com/java-exercises/collection/java-collection-hash-map-exercise-12.php)

### CC:

{% embed url="<https://www.hackerrank.com/challenges/phone-book/problem>" %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://gyansetu-core-java-for-java.gitbook.io/project/collections-framework-part-2/untitled-2.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
