java

How to check if a key exists in a HashMap in Java

In this tutorial, we are going to see how to check if a key exists in a HashMap in Java. In Java, you can use Map.containsKey() method to check if a key exists in a HashMap in Java.
 

Java Program to check if a key exists in a HashMap:
import java.util.*;

public class Main {

    public static void main(String[] args) {

        Map<Integer, String> lang = new HashMap<>();
        lang.put(1, "Java");
        lang.put(2, "PHP");
        lang.put(3, "Python");
        lang.put(4, "C++");

        if (lang.containsKey(3)) {
            System.out.println("The key exists and, its value is "+ lang.get(3));
        } else {
            System.out.println("The key does not exist!");
        }
    }
}

Output:

The key exists and, its value is Python
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *