Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVA

Java Hash Map

// Java Hash Map
// -------------

import java.util.HashMap;

public class Hash_Map {
    public static void main(String[] args) {

        HashMap<String, String> countries = new HashMap<>();

        // Inserting values
        countries.put("Turkey", "Ankara");
        countries.put("USA", "Washington, D.C.");
        countries.put("Russia", "Moscow");
        countries.put("China", "Beijing");
        countries.put("India", "New Dehli");
        // Printing the entire HashMap
        System.out.println(countries);

        System.out.println();

        // Removing items in Hashmap
        countries.remove("India");
        // Printing the entire HashMap
        System.out.println(countries);

        System.out.println();

        // Finding and Printing specific item in Hashmap
        System.out.println(countries.get("Russia")); // this will print its value

        System.out.println();

        // Printing the Size of HashMap
        System.out.println("Size: " + countries.size());

        System.out.println();

        // Replacing Values in Hashmap
        countries.replace("USA", "Detroit");
        // Printing the entire HashMap after replacing value
        System.out.println(countries);

        System.out.println();

        // Checking for some key's existence in HashMap and Printing the result
        System.out.println(countries.containsKey("Pakistan"));

        System.out.println();

        // Checking for some value's existence in HashMap and Printing the result
        System.out.println(countries.containsValue("Beijing"));

        System.out.println();

        // Printing the entire Hasmap Line by Line
        for (String i : countries.keySet()) {
            System.out.print(i + "=");
            System.out.println(countries.get(i));
        }

        System.out.println();

        // Delete All values in HashMap And Printing To see Result
        countries.clear();
        System.out.println(countries);

    }
}
 
PREVIOUS NEXT
Tagged: #Java #Hash #Map
ADD COMMENT
Topic
Name
7+9 =