Reading history

Java Collections Framework Overview: Choosing the Right Collection

6 min read 0 views

Compare Java's List, Set, Map, Queue and Deque classes, their ordering and speed, immutable collections, and useful helpers in the Collections class.

Java has a collection for almost every job: lists, sets, maps, queues, stacks, each in several flavours. Picking the right one makes code shorter and much faster; picking the wrong one leads to slow lookups, lost order or surprise exceptions. This lesson is a map of the Java Collections Framework: the main interfaces, how the common classes differ, how fast their operations are, and the Collections helper class.

In this lesson you will learn

  • The main interfaces: List, Set, Map, Queue and Deque
  • How ordering differs between Hash, Linked and Tree versions
  • Typical speed of common operations
  • Immutable collections and read-only views
  • Handy methods in the Collections class

This lesson brings together ArrayList, HashMap, HashSet and TreeSet and queues.

One Data Set, Many Collections

import java.util.*;

public class Main {
    public static void main(String[] args) {
        String[] visits = {"Dhaka", "Sylhet", "Dhaka", "Khulna", "Barishal", "Sylhet", "Dhaka"};

        List<String> list = new ArrayList<>(Arrays.asList(visits));   // keeps order and duplicates
        Set<String> hash = new HashSet<>(list);                        // unique, no fixed order
        Set<String> linked = new LinkedHashSet<>(list);                // unique, first-seen order
        Set<String> tree = new TreeSet<>(list);                        // unique, sorted

        System.out.println("ArrayList:     " + list);
        System.out.println("LinkedHashSet: " + linked);
        System.out.println("TreeSet:       " + tree);
        System.out.println("HashSet size:  " + hash.size() + " (order not guaranteed)");

        Map<String, Integer> counts = new TreeMap<>();
        for (String city : visits) counts.merge(city, 1, Integer::sum);
        System.out.println("TreeMap counts: " + counts);

        Deque<String> stack = new ArrayDeque<>();
        stack.push("page1"); stack.push("page2"); stack.push("page3");
        System.out.println("Back button pops: " + stack.pop());

        Queue<Integer> pq = new PriorityQueue<>(List.of(40, 10, 30, 20));
        System.out.print("PriorityQueue polls: ");
        while (!pq.isEmpty()) System.out.print(pq.poll() + " ");
        System.out.println();
    }
}

Output

ArrayList:     [Dhaka, Sylhet, Dhaka, Khulna, Barishal, Sylhet, Dhaka]
LinkedHashSet: [Dhaka, Sylhet, Khulna, Barishal]
TreeSet:       [Barishal, Dhaka, Khulna, Sylhet]
HashSet size:  4 (order not guaranteed)
TreeMap counts: {Barishal=1, Dhaka=3, Khulna=1, Sylhet=2}
Back button pops: page3
PriorityQueue polls: 10 20 30 40
  • ArrayList keeps every visit in order, duplicates included.
  • All three sets keep each city once, but order differs: LinkedHashSet remembers the order cities were first added, TreeSet sorts them, and HashSet promises no particular order at all.
  • TreeMap with merge counts the visits per city and keeps the keys sorted.
  • ArrayDeque works as a stack: the last page pushed is the first popped, just like a browser’s Back button.
  • PriorityQueue always hands out the smallest element first, whatever order they were added in.

Choosing a Collection

You needUseTypical speed
An ordered list, access by positionArrayListget(i) fast; insert in the middle slow
Unique items, fast “contains?”HashSetadd / contains / remove fast
Unique items in insertion orderLinkedHashSetFast, slightly more memory
Unique items always sortedTreeSetSlower (log n), but supports first, last, ranges
Key → value lookupHashMap (or LinkedHashMap, TreeMap)get / put fast (TreeMap: log n)
Stack or queue at both endsArrayDequepush / pop / offer / poll fast
Always take the smallest or most urgentPriorityQueueadd / poll log n

“Fast” here means constant time on average: it stays roughly the same speed whether the collection holds 10 items or 10 million. “log n” grows very slowly; for a million items it is about 20 steps.

Speed and the Collections Class

import java.util.*;

public class Main {
    public static void main(String[] args) {
        // Membership test: list scans every element, set jumps straight to it
        int n = 200_000;
        List<Integer> list = new ArrayList<>();
        Set<Integer> set = new HashSet<>();
        for (int i = 0; i < n; i++) { list.add(i); set.add(i); }

        int found = 0;
        long t0 = System.nanoTime();
        for (int i = 0; i < 2_000; i++) if (list.contains(n - 1 - i)) found++;
        long listMs = (System.nanoTime() - t0) / 1_000_000;

        t0 = System.nanoTime();
        for (int i = 0; i < 2_000; i++) if (set.contains(n - 1 - i)) found++;
        long setMs = (System.nanoTime() - t0) / 1_000_000;

        System.out.println("Found " + found + " items");
        System.out.println("HashSet faster than ArrayList for contains(): " + (setMs < listMs));

        // Immutable collections and the Collections utility class
        List<String> fixed = List.of("red", "green", "blue");
        try {
            fixed.add("pink");
        } catch (UnsupportedOperationException e) {
            System.out.println("List.of(...) cannot be changed");
        }
        List<Integer> nums = new ArrayList<>(List.of(5, 3, 9, 3, 7));
        Collections.sort(nums);
        System.out.println("sorted " + nums + ", max " + Collections.max(nums)
                + ", count of 3 = " + Collections.frequency(nums, 3));
        Collections.reverse(nums);
        System.out.println("reversed " + nums);
        List<Integer> readOnly = Collections.unmodifiableList(nums);
        nums.add(1);
        System.out.println("read-only view sees the change: " + readOnly);
    }
}

Output

Found 4000 items
HashSet faster than ArrayList for contains(): true
List.of(...) cannot be changed
sorted [3, 3, 5, 7, 9], max 9, count of 3 = 2
reversed [9, 7, 5, 3, 3]
read-only view sees the change: [9, 7, 5, 3, 3, 1]
  • list.contains(x) checks elements one by one, so with 200,000 items it does up to 200,000 comparisons each time. set.contains(x) jumps straight to the right bucket. The program times both and confirms the set is faster. If your code often asks “is this item in here?”, use a set.
  • List.of(...) creates an immutable list. Any attempt to add, remove or change it throws UnsupportedOperationException.
  • The Collections class has static helpers: sort, reverse, max, min, frequency, shuffle and more.
  • Collections.unmodifiableList(nums) is only a read-only view. You cannot change the list through it, but changes to nums still show through. List.copyOf(nums) makes a true immutable copy.

Common Mistakes

  1. Using a List for lookups in a loop, which turns an O(n) job into O(n²).
  2. Relying on HashSet or HashMap order. Use the Linked or Tree versions when order matters.
  3. Declaring variables as the concrete class everywhere. Write List<String> names = new ArrayList<>(), so you can switch implementation later.
  4. Mutating keys or elements stored in a hash-based collection, which makes them impossible to find.

Practice Exercises

Exercise 1. Remove duplicate words from a sentence but keep the order in which words first appear.

Show answer
String s = "to be or not to be";
Set<String> unique = new LinkedHashSet<>(Arrays.asList(s.split(" ")));
System.out.println(String.join(" ", unique));   // to be or not

Exercise 2. Which collection would you use for a leaderboard that always shows players sorted by score, with fast updates?

Show answer

A TreeMap<Integer, List<String>> from score to players (or a TreeSet with a comparator on score then name). Both keep entries sorted as you add and remove them, in log n time.

Frequently Asked Questions

Should I ever use LinkedList?

Rarely. ArrayDeque is usually faster for queues and stacks, and ArrayList is faster for most list work because its elements sit next to each other in memory. LinkedList helps mainly when you insert or remove in the middle through an iterator.

What are Vector and Hashtable?

Old collection classes from Java 1.0 with built-in locking. They still work but are rarely used in new code. Use ArrayList and HashMap, or the java.util.concurrent classes when threads share data.

Summary

  • List keeps order and duplicates; Set keeps unique items; Map links keys to values.
  • Hash = fastest, no order; Linked = insertion order; Tree = sorted.
  • Use a Set or Map for frequent lookups, not a List.
  • List.of and List.copyOf are immutable; unmodifiableList is a read-only view.

Next: Annotations and Reflection in Java.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *