The java.util Map put method is part of the Map interface in Java which allows you to associate key-value pairs. The put method is used to insert a new key-value pair into the map or update an existing one if the key already exists. It accepts two parameters: the key and the value.
Example 1:
import java.util.*;
public class MapExample { public static void main(String[] args) { Map map = new HashMap<>(); map.put("Alice", 24); map.put("Bob", 30); map.put("Charlie", 20);
In this example, we create a HashMap object to store the age of three people. We use the put method to add key-value pairs to the map. We then update Bob's age using the put method again with the same key.
Example 2:
import java.util.*;
public class MapExample { public static void main(String[] args) { Map map = new TreeMap<>(); map.put(1, "Alice"); map.put(2, "Bob"); map.put(3, "Charlie");
In this example, we create a TreeMap object to store the names of three people. We use the put method to add key-value pairs to the map. Since TreeMap is sorted based on the natural ordering of its keys, the output shows the map in ascending order.
The java.util.Map.put method is part of the Java Collections Framework and can be found in the java.util package library.
Java Map.put - 30 examples found. These are the top rated real world Java examples of java.util.Map.put extracted from open source projects. You can rate examples to help us improve the quality of examples.