Command Palette

Search for a command to run...

Back to the lesson: Topic 9.13 — Choosing the Right Collection
Core Java · Example 2 of 4

An LRU cache with LinkedHashMap

Choosing a collection comes down to four questions: duplicates or not, does order matter (and which order), how will you look things up, and do several threads share it? The answers point to ArrayList, HashMap, HashSet, LinkedHashMap, TreeMap, ArrayDeque or PriorityQueue almost every time.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Pick and justify a collection for each: (a) the last 10 search terms, newest first; (b) unique visitor IDs; (c) a leaderboard sorted by score; (d) tasks processed in arrival order by worker threads.

02

Count characters in "mississippi" and print the counts in alphabetical order.

Explain it without notes

01

Walk through how you would choose between HashMap, LinkedHashMap and TreeMap.

02

Why is ArrayDeque usually preferred over Stack and LinkedList?

03

Why should you declare variables as List or Map rather than ArrayList or HashMap?

An LRU cache with LinkedHashMap
Sign in to run this example in your browser.

Expected output

{a=1, c=3}