Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (6.5k points)
What are hashmaps in JAVA?

1 Answer

0 votes
by (11.3k points)
edited by

HashMaps in JAVA are Map Based Collection Classes that have the property of storing Key and Value pairs with keys being unique having respective values assigned to them. The format is HashMap<Key, Value>. This does not ensure an ordered arrangement of Map elements and it allows null keys and values. The concept is similar to that of a HashTable. The following code creates a simple hashmap in JAVA:

import java.util.HashMap;
import java.util.Map;

public class CreateHashMapExample {
    public static void main(String[] args) {
        // Creating a HashMap
        Map<String, Integer> numberMapping = new HashMap<>();

        // Adding key-value pairs to a HashMap
        numberMapping.put("One", 1);
        numberMapping.put("Two", 2);
        numberMapping.put("Three", 3);

        // Add a new key-value pair only if the key does not exist in the HashMap, or is mapped to `null`
        numberMapping.putIfAbsent("Four", 4);

        System.out.println(numberMapping);
    }
}

What the code has done is assigned possibly unordered unique key values to the words "one", "two", "three" and "four" as 1,2,3 and 4 respectively in the form of an internalized hash table.

# Output
{One=1, Four=4, Two=2, Three=3}

To understand these JAVA concepts in a very simplistic manner, you can sign up for the Intellipaat Java course and check out this tutorial video:

Related questions

0 votes
1 answer
asked May 17, 2023 in Java by vyeshma (32.3k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Feb 15, 2021 in Java by sheela_singh (9.5k points)
0 votes
0 answers

Browse Categories

...