Java Map put() example

In this guide, you will learn about the Map put() method in Java programming and how to use it with an example.

1. Map put() Method Overview


The put() method of the Java Map interface associates the specified value with the specified key in the map.


V previousValue = map.put(K key, V value);


- key: The key with which the specified value is to be associated.

- value: The value to be associated with the specified key.

Key Points:

- If the map previously contained a mapping for the key, the old value is replaced.

- The method returns the previous value associated with the key, or null if there was no mapping for the key.

- A map cannot contain duplicate keys; each key can map to at most one value.

- It can be used to add new key-value pairs or update the value of existing keys.

2. Map put() Method Example

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

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

        // Putting new key-value pairs
        fruitsCount.put("Apple", 10);
        fruitsCount.put("Banana", 5);
        System.out.println(fruitsCount);  // {Apple=10, Banana=5}

        // Updating the value of an existing key
        fruitsCount.put("Apple", 12);
        System.out.println(fruitsCount);  // {Apple=12, Banana=5}

        // Checking the return value of put()
        Integer previousValue = fruitsCount.put("Apple", 15);
        System.out.println("Previous count of Apples: " + previousValue);  // Previous count of Apples: 12


{Apple=10, Banana=5}
{Apple=12, Banana=5}
Previous count of Apples: 12


In this example:

1. We create a HashMap of fruits and their counts. We then use the put() method to add two key-value pairs: "Apple" with a count of 10 and "Banana" with a count of 5.

2. We update the count of "Apple" to 12 using the put() method. Since the key "Apple" already exists in the map, its value is updated.

3. We then demonstrate the return value of the put() method. When updating the count of "Apple" again to 15, the put() method returns the previous count of 12.

The put() method offers a straightforward way to add or update key-value pairs in a map. It's an essential method when working with maps as it provides flexibility in managing the data within them.

Related Map Interface methods

Java Map put() example
Java Map get() example
Java Map remove() example
Java Map containsKey() example
Java Map containsValue() example
Java Map keySet() example
Java Map values() example
Java Map entrySet() example