Lists, sets and queues in practice
Lists keep insertion order and allow duplicates.
ArrayList: fast access by position; the default choice.List.of(…): fixed and unmodifiable, ideal for constants.
Sets reject duplicates.
HashSet: fastest, no order.LinkedHashSet: remembers insertion order.TreeSet: sorted, withfirst(),ceiling(x)andheadSet(x).
Queues and deques hand out items in order.
ArrayDeque: a queue (FIFO withofferandpoll) or a stack (LIFO withpushandpop).PriorityQueue: always gives the smallest, or highest-priority, item next.
Remove items safely with removeIf or an Iterator. Java 21's sequenced collections add getFirst(), getLast() and reversed() to lists, deques and ordered sets.
Example
List<String> names = new ArrayList<>(List.of("Ravi", "Asha", "Kabir", "Asha"));
names.removeIf(n -> n.startsWith("K"));
Set<String> unique = new LinkedHashSet<>(names); // [Ravi, Asha]
TreeSet<Integer> scores = new TreeSet<>(List.of(55, 72, 91, 38));
System.out.println(scores.ceiling(60)); // 72: the smallest value >= 60
System.out.println(scores.headSet(60)); // [38, 55]
Deque<String> history = new ArrayDeque<>(); // a browser's back button
history.push("/home");
history.push("/courses");
history.push("/courses/java");
history.pop(); // back to /courses
record Job(String name, int priority) {}
PriorityQueue<Job> jobs = new PriorityQueue<>(Comparator.comparingInt(Job::priority).reversed());
jobs.add(new Job("email", 1));
jobs.add(new Job("payment", 10));
System.out.println(jobs.poll().name()); // payment
System.out.println(names.getLast()); // Java 21+Common mistake
Using Stack or LinkedList as a stack. Stack is a synchronized legacy class; ArrayDeque is faster and recommended.
Under the hood
Iterating a PriorityQueue doesn't give sorted order; only repeated poll() does, because it's a binary heap (O(log n) insert and poll, O(1) peek). ArrayDeque rejects null because null means "empty" from poll(). For thread-safe hand-offs between threads, use a BlockingQueue such as LinkedBlockingQueue.
Check yourself
Which class is recommended for a stack?
How this connects
Know these first
Where this leads
You've reached the end of this thread. Try a learning path for what's next.
Part of Java from zero, Upgrade from Java 8 to Java 25.
Was this lesson helpful?
Finished reading? Mark it complete to track your progress.