Header Ads

Header ADS

4.c:write a program to demonstrate the method of map interface java ?

 import java.util.HashMap;

import java.util.Map;


public class MapDemo {

    public static void main(String[] args) {

        // Create a HashMap to store student names and their corresponding grades

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


        // Add entries to the map

        studentGrades.put("Alice", 90);

        studentGrades.put("Bob", 85);

        studentGrades.put("Charlie", 75);

        studentGrades.put("David", 92);


        // Print the map

        System.out.println("Student Grades Map: " + studentGrades);


        // Accessing values using keys

        int aliceGrade = studentGrades.get("Alice");

        System.out.println("Alice's Grade: " + aliceGrade);


        // Checking if a key exists

        boolean hasCharlie = studentGrades.containsKey("Charlie");

        System.out.println("Has Charlie? " + hasCharlie);


        // Checking if a value exists

        boolean hasGrade85 = studentGrades.containsValue(85);

        System.out.println("Has Grade 85? " + hasGrade85);


        // Removing an entry

        studentGrades.remove("Bob");

        System.out.println("Updated Student Grades Map: " + studentGrades);


        // Getting the size of the map

        int size = studentGrades.size();

        System.out.println("Number of Students: " + size);


        // Iterating over the map using a for-each loop

        System.out.println("Iterating over Student Grades Map:");

        for (Map.Entry<String, Integer> entry : studentGrades.entrySet()) {

            String studentName = entry.getKey();

            int grade = entry.getValue();

            System.out.println(studentName + ": " + grade);

        }


        // Clearing the map

        studentGrades.clear();

        System.out.println("Cleared Student Grades Map: " + studentGrades);

    }

}


No comments

Powered by Blogger.