1. Introduction
The LinkedHashMap in Java is a part of the Java Collections Framework and inherits the HashMap class. A feature that distinguishes LinkedHashMap from HashMap is its ability to maintain the order of its entries based on their insertion or access order. In this blog post, we will explore different methods of accessing the entries of a LinkedHashMap.
2. Program Steps
1. Create and populate a LinkedHashMap.
2. Access the entries using the keySet() method.
3. Access the entries using the values() method.
4. Access the entries using the entrySet() method.
5. Display each set of entries.
3. Code Program
import java.util.LinkedHashMap;
import java.util.Map;
public class AccessLinkedHashMapEntries {
public static void main(String[] args) {
// Step 1: Create and populate a LinkedHashMap
LinkedHashMap<String, String> capitals = new LinkedHashMap<>();
capitals.put("USA", "Washington DC");
capitals.put("UK", "London");
capitals.put("India", "New Delhi");
capitals.put("Canada", "Ottawa");
// Step 2: Access the entries using the keySet() method
System.out.println("Keys in the LinkedHashMap:");
for (String country : capitals.keySet()) {
System.out.println(country);
}
// Step 3: Access the entries using the values() method
System.out.println("\nValues in the LinkedHashMap:");
for (String capital : capitals.values()) {
System.out.println(capital);
}
// Step 4: Access the entries using the entrySet() method
System.out.println("\nEntries in the LinkedHashMap:");
for (Map.Entry<String, String> entry : capitals.entrySet()) {
System.out.println(entry.getKey() + " - " + entry.getValue());
}
}
}
Output:
Keys in the LinkedHashMap: USA UK India Canada Values in the LinkedHashMap: Washington DC London New Delhi Ottawa Entries in the LinkedHashMap: USA - Washington DC UK - London India - New Delhi Canada - Ottawa
4. Step By Step Explanation
Step 1: We start by creating a LinkedHashMap named capitals and populating it with some country-capital pairs.
Step 2: We use the keySet() method of the LinkedHashMap which returns a set view of the keys. Iterating over this set, we print each country (key).
Step 3: The values() method provides a collection view of the values contained in the map. We iterate over this collection and print out each capital (value).
Step 4: To access both the key and value together, we use the entrySet() method. This method returns a set view of the mappings in the map. Each element in this set is a Map.Entry object, from which we can retrieve the key and value using the getKey() and getValue() methods respectively.
The LinkedHashMap ensures that the order of the entries is based on the order in which they were inserted, which is evident in the output.