Questions or a demo for your school?Student? Sit a test
BrainBit Infotech TeachingStart free

Core Java notes · Topic 15 of 20 · 5 min read

Java collections: List, Set and Queue

Java collections notes with examples: ArrayList and LinkedList, HashSet, LinkedHashSet and TreeSet, Queue, Deque, PriorityQueue and Iterator.

Why collections?

An array has a fixed size. Real programs need groups that grow and shrink: the items in a cart, the students who joined today, the tickets waiting in a queue. The Java Collections Framework (in java.util) gives ready-made, tested data structures for this.

Collection
  List   ordered, allows duplicates, index-based    ArrayList, LinkedList
  Set    no duplicates                               HashSet, LinkedHashSet, TreeSet
  Queue  hold items for processing                   ArrayDeque, PriorityQueue, LinkedList
Map (separate family: key -> value)                  HashMap, LinkedHashMap, TreeMap

Declare variables by the interface and create the class: List<String> names = new ArrayList<>();. You can switch the class later without changing the rest of the code.

ArrayList

The most-used collection: a resizable array.

import java.util.ArrayList;
import java.util.List;

List<String> cart = new ArrayList<>();
cart.add("Notebook");
cart.add("Pen");
cart.add("Pen");                 // duplicates allowed
cart.add(1, "Ruler");            // insert at index 1
System.out.println(cart);        // [Notebook, Ruler, Pen, Pen]
System.out.println(cart.get(0)); // Notebook
cart.set(0, "Diary");            // replace
cart.remove("Pen");              // removes the first "Pen"
cart.remove(0);                  // removes by index
System.out.println(cart.size()); // 2
System.out.println(cart.contains("Ruler"));   // true

Common List methods

MethodDoes
add(x), add(i, x)add at the end, or at index i
get(i), set(i, x)read or replace by index
remove(i), remove(obj)remove by index or by value
size(), isEmpty()count, empty check
contains(x), indexOf(x)search
clear()remove everything
List.of(a, b, c)a fixed, unmodifiable list (Java 9+)

Looping

for (String item : cart) System.out.println(item);
for (int i = 0; i < cart.size(); i++) System.out.println(i + ": " + cart.get(i));
cart.forEach(System.out::println);

Integer trap: for a List<Integer>, list.remove(1) removes index 1. To remove the value 1, write list.remove(Integer.valueOf(1)).

ArrayList versus LinkedList

ArrayListLinkedList
Stored asa resizable arraya chain of nodes
get(i)fastslow (walks the chain)
add or remove at the start or middleslow (shifts elements)fast once you are at the spot
Typical usemost listsqueues, frequent inserts at the ends

When in doubt, use ArrayList.

Sets: no duplicates

import java.util.*;

Set<String> cities = new HashSet<>();
cities.add("Ranchi");
cities.add("Patna");
boolean added = cities.add("Ranchi");   // false: already there
System.out.println(cities.size());      // 2
SetOrderSpeed
HashSetno guaranteed orderfastest
LinkedHashSetthe order you added itemsfast
TreeSetsorted (natural order or a Comparator)slower
Set<Integer> marks = new TreeSet<>(List.of(72, 91, 65, 91, 80));
System.out.println(marks);   // [65, 72, 80, 91]

A quick way to remove duplicates from a list: new ArrayList<>(new LinkedHashSet<>(list)).

Set operations

Set<String> a = new HashSet<>(List.of("java", "python", "c"));
Set<String> b = new HashSet<>(List.of("python", "c", "go"));
Set<String> common = new HashSet<>(a);
common.retainAll(b);        // intersection: [python, c]
Set<String> all = new HashSet<>(a);
all.addAll(b);              // union

For your own classes in a HashSet, override equals and hashCode.

Queue and Deque

A queue is first-in, first-out (FIFO), like a ticket counter.

Queue<String> line = new ArrayDeque<>();
line.offer("Asha");
line.offer("Ravi");
System.out.println(line.peek());   // Asha (look, do not remove)
System.out.println(line.poll());   // Asha (remove)
System.out.println(line);          // [Ravi]

offer, poll and peek return false or null instead of throwing when the queue is full or empty.

A Deque (double-ended queue) works at both ends and also makes a good stack (last-in, first-out):

Deque<Integer> stack = new ArrayDeque<>();
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println(stack.pop());   // 3

Prefer ArrayDeque to the old Stack class.

PriorityQueue

Removes the smallest item first (or the highest priority with a Comparator):

PriorityQueue<Integer> pq = new PriorityQueue<>(List.of(40, 10, 30));
System.out.println(pq.poll());   // 10

Iterator: removing while looping

Removing from a list inside a for-each loop throws ConcurrentModificationException. Use an Iterator or removeIf:

List<Integer> marks = new ArrayList<>(List.of(35, 72, 28, 90));
Iterator<Integer> it = marks.iterator();
while (it.hasNext()) {
    if (it.next() < 40) it.remove();
}
// or, in one line:
marks.removeIf(m -> m < 40);

The Collections class

List<Integer> nums = new ArrayList<>(List.of(5, 2, 9, 1));
Collections.sort(nums);                 // [1, 2, 5, 9]
Collections.reverse(nums);              // [9, 5, 2, 1]
Collections.shuffle(nums);
int max = Collections.max(nums);        // 9
int freq = Collections.frequency(nums, 5);

Common mistakes

  • Declaring ArrayList<int>; use ArrayList<Integer>.
  • Changing a list inside a for-each loop over the same list.
  • Trying to add to List.of(...): it is unmodifiable and throws UnsupportedOperationException.
  • Expecting HashSet to keep insertion order.
  • Using a HashSet of your own objects without equals and hashCode, so duplicates are not detected.

Key points

  • List keeps order and duplicates; Set removes duplicates; Queue processes items in order.
  • ArrayList is the default list; HashSet the default set; ArrayDeque the default queue and stack.
  • TreeSet keeps items sorted; LinkedHashSet keeps insertion order.
  • Use Iterator.remove() or removeIf to delete while looping.
  • Collections has sort, reverse, max, min, shuffle and frequency.

Practice questions

1. Which collection would you use for a list of unique roll numbers kept in sorted order?

TreeSet<Integer>.

2. What is printed? List<Integer> l = new ArrayList<>(List.of(10, 20, 30)); l.remove(1); System.out.println(l);

[10, 30]. remove(1) removes index 1.

3. Remove duplicates from List<String> names but keep the original order.
List<String> unique = new ArrayList<>(new LinkedHashSet<>(names));
4. Use a stack to reverse the word "JAVA".
Deque<Character> st = new ArrayDeque<>();
for (char c : "JAVA".toCharArray()) st.push(c);
StringBuilder sb = new StringBuilder();
while (!st.isEmpty()) sb.append(st.pop());
System.out.println(sb);   // AVAJ
5. What is the difference between poll() and remove() on an empty queue?

poll() returns null; remove() throws NoSuchElementException.