Java / Java 21 Collection Framework features Interview questions
How do you use putFirst() on a LinkedHashMap?
Call putFirst(key, value) on any LinkedHashMap instance to insert a new entry, or move an existing one, to the front of its iteration order.
LinkedHashMap<String, Integer> recent = new LinkedHashMap<>(); recent.put("x", 1); recent.put("y", 2); recent.putFirst("z", 3); // order becomes z, x, y
This is handy for building a "most recently used" list at the front, without manually removing and re-inserting the entry yourself.
Note that by default a LinkedHashMap uses insertion order; if it's constructed with access-order mode enabled, reads via get() also move entries, which can interact with what "first" and "last" mean at any given moment.
More Related questions...