java dictionary

www.‮uttual‬ri.com
java dictionary

In Java, a dictionary is a collection of key-value pairs that can be used to store data. A dictionary is also known as a map or an associative array.

The java.util.Map interface and the java.util.HashMap class are commonly used to implement dictionaries in Java.

Here's an example of how to use a HashMap to create a dictionary:

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);

// Retrieve the value for a given key
int value = dictionary.get("banana");
System.out.println("Value for key 'banana': " + value);  // Outputs: Value for key 'banana': 2

// Check if the dictionary contains a specific key
boolean containsKey = dictionary.containsKey("apple");
System.out.println("Dictionary contains key 'apple': " + containsKey);  // Outputs: Dictionary contains key 'apple': true

// Check if the dictionary contains a specific value
boolean containsValue = dictionary.containsValue(3);
System.out.println("Dictionary contains value 3: " + containsValue);  // Outputs: Dictionary contains value 3: true

// Remove a key-value pair from the dictionary
dictionary.remove("apple");

// Iterate over the key-value pairs in the dictionary
for (Map.Entry<String, Integer> entry : dictionary.entrySet()) {
    System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}

This will output the following:

Value for key 'banana': 2
Dictionary contains key 'apple': true
Dictionary contains value 3: true
Key: banana, Value: 2
Key: orange, Value: 3

You can also use the java.util.AbstractMap class to create a dictionary in Java.

Created Time:2017-11-03 00:14:53  Author:lautturi