In Java, you can directly initialize a HashMap using its literal syntax by using the curly braces {} and providing key-value pairs separated by commas. Here's an example of how you can do it:
java
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
// Initializing a HashMap using literal syntax
HashMap<String, Integer> ages = new HashMap<String, Integer>() {
{
put("Alice", 25);
put("Bob", 30);
put("Carol", 28);
}
};
// Accessing values from the HashMap
System.out.println("Age of Alice: " + ages.get("Alice"));
System.out.println("Age of Bob: " + ages.get("Bob"));
System.out.println("Age of Carol: " + ages.get("Carol"));
}
}
In this example, we create a HashMap named ages using the literal syntax within curly braces. The key-value pairs are defined inside the curly braces using the put() method. You'll notice that this syntax involves creating an anonymous inner class with an instance initializer block ({}) to achieve the direct initialization.
Please note that while this syntax allows for direct initialization of a HashMap, it might not be the most concise or readable approach, especially for small maps. For larger maps or cases where you want to create a HashMap with a lot of key-value pairs, consider using the regular put() method calls or utilizing a library like Google Guava's ImmutableMap for improved readability.
java
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
// Initializing a HashMap using literal syntax
HashMap<String, Integer> ages = new HashMap<String, Integer>() {
{
put("Alice", 25);
put("Bob", 30);
put("Carol", 28);
}
};
// Accessing values from the HashMap
System.out.println("Age of Alice: " + ages.get("Alice"));
System.out.println("Age of Bob: " + ages.get("Bob"));
System.out.println("Age of Carol: " + ages.get("Carol"));
}
}
In this example, we create a HashMap named ages using the literal syntax within curly braces. The key-value pairs are defined inside the curly braces using the put() method. You'll notice that this syntax involves creating an anonymous inner class with an instance initializer block ({}) to achieve the direct initialization.
Please note that while this syntax allows for direct initialization of a HashMap, it might not be the most concise or readable approach, especially for small maps. For larger maps or cases where you want to create a HashMap with a lot of key-value pairs, consider using the regular put() method calls or utilizing a library like Google Guava's ImmutableMap for improved readability.
Comments
Post a Comment