A recent files menu should move a reopened file to the top instead of showing it twice. Once the menu is full, opening a new file should remove the oldest entry. In Java 21, a LinkedHashMap can do both through the SequencedMap interface. See the Java 21 SequencedMap API.
1. Move a reopened file to the newest position
Use a LinkedHashMap to store each file name and its path. The example keeps the oldest entry first and the newest entry last.
On a default LinkedHashMap, calling put() for an existing key changes its value but leaves it in the same position. Calling putLast() also moves the entry to the end. That means reopening notes.txt makes it the newest entry without adding a duplicate. See the Java 21 LinkedHashMap API.
2. Remove the oldest entry when the list is full
After recording a file, check the map’s size. If it exceeds the limit, call pollFirstEntry() to remove and return the oldest entry. Use reversed() when displaying the menu so the newest entry appears first.
3. Run the complete example
Save this code as RecentFilesExample.java. The paths are sample strings; the program does not open any files.
import java.util.LinkedHashMap;
import java.util.SequencedMap;
public class RecentFilesExample {
private static final int LIMIT = 3;
public static void main(String[] args) {
SequencedMap<String, String> recent = new LinkedHashMap<>();
remember(recent, "notes.txt", "/work/notes.txt");
remember(recent, "plan.txt", "/work/plan.txt");
remember(recent, "ideas.txt", "/work/ideas.txt");
remember(recent, "notes.txt", "/work/notes.txt");
System.out.println("After reopening: " + recent.sequencedKeySet());
var removed = remember(recent, "draft.txt", "/work/draft.txt");
System.out.println("Removed: " + removed);
System.out.println("Newest first: " + recent.reversed().sequencedKeySet());
}
private static String remember(SequencedMap<String, String> recent,
String name, String path) {
recent.putLast(name, path);
if (recent.size() > LIMIT) {
return recent.pollFirstEntry().getKey();
}
return null;
}
}
Compile and run it from the directory containing the file:
javac --release 21 RecentFilesExample.java
java RecentFilesExample
Output:
After reopening: [plan.txt, ideas.txt, notes.txt]
Removed: plan.txt
Newest first: [draft.txt, notes.txt, ideas.txt]
Reopening notes.txt makes plan.txt the oldest entry. Adding draft.txt takes the map over its three-file limit, so plan.txt is removed.
Best practices
- Use a full path or another stable identifier as the key in a real app. Two folders can contain files with the same name.
- Update the list after a file opens successfully so failed attempts do not appear in the menu.
- Treat
reversed()as a live view. If you need a list that stays the same when the map changes, take a snapshot withList.copyOf(recent.reversed().sequencedKeySet()).
