The LinkedHashMap class in Java is a implementation of the Map interface that stores key-value pairs in a hash table, with a linked list used to maintain the insertion order of the elements. It allows you to store and retrieve elements based on a key, and provides constant-time performance for the basic operations (get and put).
Here is an example of how to use a LinkedHashMap in Java:
import java.util.LinkedHashMap;
public class Main {
public static void main(String[] args) {
// Create a LinkedHashMap
LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
// Add some elements to the map
map.put("apple", 1);
map.put("banana", 2);
map.put("orange", 3);
// Iterate through the map in insertion order
for (String key : map.keySet()) {
int value = map.get(key);
System.out.println(key + ": " + value);
}
// Retrieve an element from the map
int value = map.get("banana");
System.out.println("The value for 'banana' is: " + value);
// Remove an element from the map
map.remove("apple");
// Check if the map contains a specific key
boolean containsKey = map.containsKey("orange");
System.out.println("The map contains the key 'orange': " + containsKey);
}
}
In this example, we create a LinkedHashMap that maps strings (the keys) to integers (the values). We add some elements to the map and iterate through the map in insertion order. We also retrieve an element by its key, remove an element from the map, and check if the map contains a specific key.
Note that the LinkedHashMap class is not synchronized, which means that it is not thread-safe. If you need a thread-safe map, you can use the Collections.synchronizedMap() method to wrap a LinkedHashMap in a synchronized map.