Maps

Maps

In Java, the Map interface is used to represent a collection of key-value pairs. It is an unordered collection that does not allow duplicate keys. The Map interface is part of the Java Collections Framework and is implemented by several classes such as HashMap, TreeMap, and LinkedHashMap.

To use the Map interface, you first need to import the java.util.Map package. Here’s an example of how to create a HashMap and add key-value pairs to it:

import java.util.HashMap;

import java.util.Map;

public class MapExample {

    public static void main(String[] args) {

        Map<String, Integer> map = new HashMap<>();

        map.put(“Alice”, 25);

        map.put(“Bob”, 30);

        map.put(“Charlie”, 35);

        System.out.println(map.get(“Bob”)); // prints 30

        System.out.println(map.containsKey(“Dave”)); // prints false

        System.out.println(map.containsValue(25)); // prints true

    }

}

In the above example, we first create a HashMap that maps String keys to Integer values. We then add three key-value pairs to the map using the put() method. We can retrieve the value associated with a key using the get() method. We can also check if a key or value is present in the map using the containsKey() and containsValue() methods, respectively.

Apply for Core Java Developer Certification Now!!

https://www.vskills.in/certification/certified-core-java-developer

Back to Tutorial

ArrayList
Basics of threads

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?