A dictionary, also known as a map or associative array, is a collection of key-value pairs. In Java, you can use the java.util.HashMap
class to implement a dictionary.
Here's an example of how to initialize a dictionary in Java:
import java.util.HashMap; // Initialize an empty dictionary HashMap<String, Integer> dictionary = new HashMap<>(); // Add key-value pairs to the dictionary dictionary.put("apple", 1); dictionary.put("banana", 2); dictionary.put("orange", 3);
This creates a dictionary with three key-value pairs: "apple" -> 1, "banana" -> 2, and "orange" -> 3.
You can also initialize a dictionary with a set of key-value pairs using the putAll()
method:
import java.util.HashMap; // Initialize a dictionary with a set of key-value pairs HashMap<String, Integer> dictionary = new HashMap<>(); dictionary.putAll(Map.ofEntries( Map.entry("apple", 1), Map.entry("banana", 2), Map.entry("orange", 3) ));
This creates a dictionary with the same key-value pairs as in the previous example.
You can also use the java.util.Map
interface and the java.util.AbstractMap
class to create a dictionary in Java.