Choosing the Right Collection

Naveen AnamaneniUpdated · 5 min read

Java has many collection classes, and choosing the right one makes code simpler and faster. The choice comes down to a few questions: Do you need key-value pairs? Are duplicates allowed? Does the order matter? Will several threads share it? In this lesson, you will learn a simple decision guide, see the best class for common situations, and finish this chapter with a summary of every collection covered.

Step 1: What Kind of Collection?

Answer three questions to pick the family, then one about order to pick the class
  1. Pairs of key and value? Use a Map.
  2. Only unique elements? Use a Set.
  3. Processing elements from the ends or by priority? Use a Deque or PriorityQueue.
  4. Otherwise, an ordered sequence with positions: use a List.

Step 2: Which Class?

NeedBest choice
A general listArrayList
A queue (first in, first out)ArrayDeque
A stack (last in, first out)ArrayDeque
Always take the smallest or most urgentPriorityQueue
Unique elements, order doesn't matterHashSet
Unique elements in insertion orderLinkedHashSet
Unique elements, sorted, or nearest-value searchTreeSet
Unique enum valuesEnumSet
Key-value lookup, order doesn't matterHashMap
Key-value in insertion order, or an LRU cacheLinkedHashMap
Sorted keys, or nearest-key searchTreeMap
Enum keysEnumMap
A fixed list of constantsList.of(...)
Shared map between threadsConcurrentHashMap
Shared list, many reads, few writesCopyOnWriteArrayList
Producer and consumer threadsArrayBlockingQueue / LinkedBlockingQueue

Example: One Problem, the Right Collections

Let's see an example: a library records which members borrowed which books, in order, and must quickly answer three questions.

Library.java▶ Try it
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
 
public class Library {
    public static void main(String[] args) {
        List<String[]> loans = new ArrayList<>();
        loans.add(new String[] {"Navika", "Java Basics"});
        loans.add(new String[] {"Srihitha", "SQL Guide"});
        loans.add(new String[] {"Navika", "Data Structures"});
        loans.add(new String[] {"Advitha", "Java Basics"});
 
        Set<String> titles = new TreeSet<>();
        Map<String, List<String>> byMember = new HashMap<>();
        for (String[] loan : loans) {
            titles.add(loan[1]);
            byMember.computeIfAbsent(loan[0], k -> new ArrayList<>())
                    .add(loan[1]);
        }
 
        System.out.println("Loans in order: " + loans.size());
        System.out.println("Distinct titles, sorted: " + titles);
        System.out.println("Navika borrowed: " + byMember.get("Navika"));
    }
}
Output
Loans in order: 4
Distinct titles, sorted: [Data Structures, Java Basics, SQL Guide]
Navika borrowed: [Java Basics, Data Structures]

Explanation: The loans are a sequence where duplicates and order matter, so an ArrayList holds them. Distinct titles in sorted order call for a TreeSet. "Which books did this member borrow?" is a lookup by key, so a HashMap from member to a list of books answers it in one step.

Common Mistakes

Using a List and calling contains to prevent duplicates. Use a Set.

Using Stack, Vector or Hashtable in new code. Use ArrayDeque, ArrayList and HashMap or ConcurrentHashMap.

Using TreeMap "just in case" sorting is needed. It's slower; sort when you need to, or switch when sorting becomes frequent.

Interview Corner

How do you choose between List, Set and Map?

Use a Map when data is looked up by a key. Otherwise, use a Set when elements must be unique, and a List when duplicates are allowed and position or insertion order matters. Then pick the implementation by order requirements: hash-based (HashSet, HashMap) for no order, linked (LinkedHashSet, LinkedHashMap) for insertion order, tree-based (TreeSet, TreeMap) for sorted order. For shared data, use the concurrent versions.

Practice

  1. Easy: Choose a collection for each: the moves in a game so you can undo them; the unique visitors to a website; a dictionary of words and meanings shown alphabetically.
  2. Harder: Design the collections for a small online shop: products by ID, a cart that keeps the order items were added, the set of categories, and a queue of orders to ship. Write the declarations and explain each choice.

Quick check: Choosing a collection

4 questions
1You need unique usernames and fast lookups. Which class?
2You need a stack in new code. Which class?
3Keys must stay sorted alphabetically. Which class?
4Which is the default general-purpose list?

Key Takeaways

Was this tutorial helpful?

Lesson 301 of 482