Preview:
import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHashMapExample {
    public static void main(String[] args) {
        // Creating a LinkedHashMap
        LinkedHashMap<Integer, String> linkedHashMap = new LinkedHashMap<>();

        // Adding elements to the LinkedHashMap
        linkedHashMap.put(1, "Apple");
        linkedHashMap.put(2, "Banana");
        linkedHashMap.put(3, "Orange");
        linkedHashMap.put(4, "Grapes");
        linkedHashMap.put(5, "Mango");

        // Displaying the elements in the LinkedHashMap
        System.out.println("LinkedHashMap elements:");
        for (Map.Entry<Integer, String> entry : linkedHashMap.entrySet()) {
            System.out.println(entry.getKey() + " => " + entry.getValue());
        }

        // Removing an element from the LinkedHashMap
        String removedElement = linkedHashMap.remove(2);
        System.out.println("Removed element with key 2: " + removedElement);

        // Checking if a key exists in the LinkedHashMap
        boolean containsKey = linkedHashMap.containsKey(3);
        System.out.println("LinkedHashMap contains key 3: " + containsKey);

        // Checking if a value exists in the LinkedHashMap
        boolean containsValue = linkedHashMap.containsValue("Banana");
        System.out.println("LinkedHashMap contains value 'Banana': " + containsValue);

        // Getting a value from the LinkedHashMap
        String value = linkedHashMap.get(4);
        System.out.println("Value associated with key 4: " + value);

        // Iterating over the elements in the LinkedHashMap using an Iterator
        System.out.println("Iterating over LinkedHashMap elements using Iterator:");
        for (Map.Entry<Integer, String> entry : linkedHashMap.entrySet()) {
            System.out.println(entry.getKey() + " => " + entry.getValue());
        }

        // Clearing the LinkedHashMap
        linkedHashMap.clear();
        System.out.println("LinkedHashMap cleared. Current size: " + linkedHashMap.size());
    }
}
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter