Using Map in Java

A Java Map is an entity that facilitates the storage of key/value pair associations. Both the keys and values in this collection are treated as objects. Each key corresponds to a singular value, enabling the fetching of a value by its key. This key-to-value association distinguishes it from other collections, such as List or Set. To insert a key/value pairing in the map, the put() method is employed, while the get() method allows for extracting a value based on its key. Various operations can be executed on maps, including verifying the presence of a key using containsKey(), purging a key/value association with remove(), and ascertaining the map's magnitude via size(). Contrary to other collections, the Map interface doesn't uphold elementary functions like add or get. Instead, it endorses unique operations tailored for key/value pair management. In this Java Map Example, we instantiate a Map entity, input data into it, and subsequently showcase a value based on its key along with the overall dimensions of the constituted map. Click Execute to run the Java Map Example online and see the result.
Using Map in Java Execute
import java.util.HashMap;
import java.util.Map;

public class MapExample {

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

        countriesAndCapitals.put("France", "Paris");
        countriesAndCapitals.put("Japan", "Tokyo");

        String capitalOfFrance = countriesAndCapitals.get("France");
        System.out.println("Capital of France: " + capitalOfFrance);

        System.out.println("Size of the map: " + countriesAndCapitals.size());
Updated: Viewed: 48 times