Practicecore
Choose a collection
Also called choosing a collection, which collection to use, choose a data structure.
Pick a collection by the operations the code does most and by their cost: a list for order, a set for membership, a map for lookup by key, then the default type of the language.
Statement
Choose a collection by the operations that the code does most often, and by what each operation costs in that collection. The Rust documentation puts it this way: "Choosing the right collection for the job requires an understanding of what each collection is good at"1. First decide the kind of collection: a list when the values have positions, a set when the main question is whether a value is present, and a map when values are found by a key. Then use the default type of that kind in the language, and change to a special type only when an operation that the code needs is slow in the default or missing from it.
Meaning
Ask three questions.
- Do the values have an order that matters, or do you read them by position? Use a list. In Java, Rust and C++ the usual list is a dynamic array, a resizable array213.
- Is each value there only once, and do you mostly ask whether a value is present? Use a set. The Python tutorial says that the basic uses of a set "include membership testing and eliminating duplicate entries"4.
- Do you look up a value by a key? Use a map. The .NET table gives a dictionary for the case "Store items as key/value pairs for quick look-up by key"5.
Then look at the ends. A list is fast at its end and slow at its front. The Python tutorial says that a list used as a queue is not efficient: "doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one)"4. Python's deque has appends and pops "from either side of the deque with approximately the same O(1) performance in either direction"6. Use a list for a stack and a deque for a queue. Rust gives the same advice: use a Vec when "You want a stack" and a VecDeque when "You want a queue"1.
Then look at order. A hash set or a hash map keeps its keys unsorted: C++ calls its hash containers "unsorted (hashed) data structures"3. Use a tree when the code needs the keys in order, or the smallest key, or all the keys in a range. Rust says to use a BTreeMap when "You want a map sorted by its keys" or "You want to be able to get a range of entries on-demand"1. To take only the largest or the smallest value each time, use a priority queue. Rust says to use a BinaryHeap when "You want a priority queue"1.
Then check the cost. The documentation of each language gives the cost of the main operations. The table below uses the Rust table1 and the .NET table5. The n is the number of elements and i is a position.
| Operation | Array list | Deque | Linked list | Hash map or set | Tree map or set |
|---|---|---|---|---|---|
| read by position | O(1) | O(1) | O(min(i, n-i)) | - | - |
| add or remove at position i | O(n-i) | O(min(i, n-i)) | O(min(i, n-i)) | - | - |
| add at the end | O(1) amortized | O(1) amortized | O(1) | - | - |
| find, add or remove by key | - | - | - | O(1) expected | O(log n) |
| find a range of keys | - | - | - | - | O(log n) |
The defaults in each language. Each row of this table is a common need, and each cell is the type that the standard library gives for it.
| Need | Python | JavaScript | Java | C# | Go | Rust | C++ |
|---|---|---|---|---|---|---|---|
| a list | list |
Array |
ArrayList |
List<T> |
slice | Vec |
std::vector |
| a queue at both ends | collections.deque |
none | ArrayDeque |
Queue<T> |
container/list |
VecDeque |
std::deque |
| a set | set |
Set |
HashSet |
HashSet<T> |
map[T]bool |
HashSet |
std::unordered_set |
| a map | dict |
Map |
HashMap |
Dictionary<TKey,TValue> |
map[K]V |
HashMap |
std::unordered_map |
| a sorted map | none | none | TreeMap |
SortedDictionary<TKey,TValue> |
none | BTreeMap |
std::map |
The sources for the table are these. Java names HashSet, ArrayList, ArrayDeque, HashMap and TreeMap as general purpose implementations2, and says that ArrayDeque "is likely to be faster than Stack when used as a stack, and faster than LinkedList when used as a queue"7. The .NET table gives Dictionary<TKey,TValue>, List<T>, Queue<T> and HashSet<T>5, and SortedDictionary<TKey,TValue> "is a binary search tree with O(log n) retrieval"8. Go has slices and maps as built-in types9. Effective Go says that "A set can be implemented as a map with value type bool"10, and container/list "implements a doubly linked list"11. In JavaScript, a Map has keys of any type, and MDN says to "Use maps over objects when keys are unknown until run time"12. In C++, vector is a "resizable contiguous array", deque is a "double-ended queue", map is a "collection of key-value pairs, sorted by keys, keys are unique", and unordered_map is a "collection of key-value pairs, hashed by keys, keys are unique"3. The Rust names are from the Rust guide1.
Examples
Each example file keeps the words of one sentence in five collections, one for each row of the second table: a list of all the words, a set of the different words, a map from each word to its count, a queue of the first words, and a sorted map of the counts.
from collections import Counter, deque
words = "the cat saw the dog and the cat ran".split()
seen = set(words) # membership, no duplicates
counts = Counter(words) # a dict from word to count
line = deque(words[:3]) # a queue: fast at both ends
first = line.popleft()
second = line.popleft()
print(f"list: {len(words)} words, third is {words[2]}")
print(f"set: {len(seen)} distinct")
print(f"map: the={counts['the']} cat={counts['cat']}")
print(f"queue: {first}, then {second}")
print("sorted:", " ".join(sorted(counts))) # Python has no sorted map: sort the keys
list: 9 words, third is saw
set: 6 distinct
map: the=3 cat=2
queue: the, then cat
sorted: and cat dog ran saw the
The files for JavaScript, Java, C#, Go, Rust and C++ use the types in the defaults table. Python, JavaScript and Go have no sorted map in the standard library, so their files sort the keys when they print them.
#include <deque>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
int main() {
std::istringstream in("the cat saw the dog and the cat ran");
std::vector<std::string> words;
for (std::string w; in >> w;) words.push_back(w);
std::unordered_set<std::string> seen(words.begin(), words.end());
std::unordered_map<std::string, int> counts;
for (const auto& w : words) ++counts[w];
std::deque<std::string> line(words.begin(), words.begin() + 3);
std::string first = line.front();
line.pop_front();
std::string second = line.front();
line.pop_front();
std::map<std::string, int> sorted(counts.begin(), counts.end());
std::cout << "list: " << words.size() << " words, third is " << words[2] << '\n';
std::cout << "set: " << seen.size() << " distinct\n";
std::cout << "map: the=" << counts["the"] << " cat=" << counts["cat"] << '\n';
std::cout << "queue: " << first << ", then " << second << '\n';
std::cout << "sorted:";
for (const auto& kv : sorted) std::cout << ' ' << kv.first;
std::cout << '\n';
}
list: 9 words, third is saw
set: 6 distinct
map: the=3 cat=2
queue: the, then cat
sorted: and cat dog ran saw the
std::vector,std::unordered_set,std::unordered_map,std::dequeandstd::mapare the standard containers for the five needs. Thestd::mapkeeps its keys sorted.
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
List<String> words = new ArrayList<>(Arrays.asList("the cat saw the dog and the cat ran".split(" ")));
Set<String> seen = new HashSet<>(words);
Map<String, Integer> counts = new HashMap<>();
for (String w : words) counts.merge(w, 1, Integer::sum);
ArrayDeque<String> line = new ArrayDeque<>(words.subList(0, 3));
String first = line.removeFirst();
String second = line.removeFirst();
TreeMap<String, Integer> sorted = new TreeMap<>(counts);
System.out.println("list: " + words.size() + " words, third is " + words.get(2));
System.out.println("set: " + seen.size() + " distinct");
System.out.println("map: the=" + counts.get("the") + " cat=" + counts.get("cat"));
System.out.println("queue: " + first + ", then " + second);
System.out.println("sorted: " + String.join(" ", sorted.keySet()));
}
}
list: 9 words, third is saw
set: 6 distinct
map: the=3 cat=2
queue: the, then cat
sorted: and cat dog ran saw the
ArrayList,HashSet,HashMap,ArrayDequeandTreeMapare the general purpose implementations. TheTreeMapkeeps its keys sorted, sokeySetgives them in order.
using System;
using System.Collections.Generic;
var words = new List<string>("the cat saw the dog and the cat ran".Split(' '));
var seen = new HashSet<string>(words);
var counts = new Dictionary<string, int>();
foreach (var w in words) counts[w] = counts.GetValueOrDefault(w) + 1;
var line = new Queue<string>(words.GetRange(0, 3));
var first = line.Dequeue();
var second = line.Dequeue();
var sorted = new SortedDictionary<string, int>(counts, StringComparer.Ordinal);
Console.WriteLine($"list: {words.Count} words, third is {words[2]}");
Console.WriteLine($"set: {seen.Count} distinct");
Console.WriteLine($"map: the={counts["the"]} cat={counts["cat"]}");
Console.WriteLine($"queue: {first}, then {second}");
Console.WriteLine("sorted: " + string.Join(" ", sorted.Keys));
list: 9 words, third is saw
set: 6 distinct
map: the=3 cat=2
queue: the, then cat
sorted: and cat dog ran saw the
List<T>,HashSet<T>,Dictionary<TKey,TValue>,Queue<T>andSortedDictionary<TKey,TValue>are inSystem.Collections.Generic.StringComparer.Ordinalsorts the keys by their characters, not by the rules of a culture.
const words = "the cat saw the dog and the cat ran".split(" ");
const seen = new Set(words); // membership, no duplicates
const counts = new Map(); // word to count
for (const w of words) counts.set(w, (counts.get(w) ?? 0) + 1);
const line = words.slice(0, 3); // no deque type: an array as a queue
const first = line.shift();
const second = line.shift();
console.log(`list: ${words.length} words, third is ${words[2]}`);
console.log(`set: ${seen.size} distinct`);
console.log(`map: the=${counts.get("the")} cat=${counts.get("cat")}`);
console.log(`queue: ${first}, then ${second}`);
console.log("sorted:", [...counts.keys()].sort().join(" ")); // no sorted map: sort the keys
list: 9 words, third is saw
set: 6 distinct
map: the=3 cat=2
queue: the, then cat
sorted: and cat dog ran saw the
- JavaScript has no deque type, so the queue is an array with
shift. AMapkeeps its keys in insertion order, so the keys must be sorted to print them in order.
package main
import (
"container/list"
"fmt"
"maps"
"slices"
"strings"
)
func main() {
words := strings.Fields("the cat saw the dog and the cat ran")
seen := map[string]bool{} // a set is a map with value type bool
counts := map[string]int{}
for _, w := range words {
seen[w] = true
counts[w]++
}
line := list.New() // a doubly linked list as a queue
for _, w := range words[:3] {
line.PushBack(w)
}
first := line.Remove(line.Front())
second := line.Remove(line.Front())
fmt.Printf("list: %d words, third is %s\n", len(words), words[2])
fmt.Printf("set: %d distinct\n", len(seen))
fmt.Printf("map: the=%d cat=%d\n", counts["the"], counts["cat"])
fmt.Printf("queue: %v, then %v\n", first, second)
fmt.Println("sorted:", strings.Join(slices.Sorted(maps.Keys(counts)), " "))
}
list: 9 words, third is saw
set: 6 distinct
map: the=3 cat=2
queue: the, then cat
sorted: and cat dog ran saw the
- Go has slices and maps as built-in types. A set is a
map[string]bool, a queue can be acontainer/list, and there is no sorted map, soslices.Sorted(maps.Keys(counts))sorts the keys. - The order of
maps.Keysis not specified, so the keys must be sorted before they are printed.
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
fn main() {
let words: Vec<&str> = "the cat saw the dog and the cat ran".split(' ').collect();
let seen: HashSet<&str> = words.iter().copied().collect();
let mut counts: HashMap<&str, usize> = HashMap::new();
for &w in &words {
*counts.entry(w).or_insert(0) += 1;
}
let mut line: VecDeque<&str> = words[..3].iter().copied().collect();
let first = line.pop_front().unwrap();
let second = line.pop_front().unwrap();
let sorted: BTreeMap<&str, usize> = counts.iter().map(|(k, v)| (*k, *v)).collect();
println!("list: {} words, third is {}", words.len(), words[2]);
println!("set: {} distinct", seen.len());
println!("map: the={} cat={}", counts["the"], counts["cat"]);
println!("queue: {}, then {}", first, second);
let keys: Vec<&str> = sorted.keys().copied().collect();
println!("sorted: {}", keys.join(" "));
}
list: 9 words, third is saw
set: 6 distinct
map: the=3 cat=2
queue: the, then cat
sorted: and cat dog ran saw the
Vec,HashSet,HashMap,VecDequeandBTreeMapare instd::collectionsor the prelude. TheBTreeMapkeeps its keys sorted.
Criticism and limits
- The big O hides the constants. Two collections with the same cost can have different speeds. Rust says that "where ties occur, Vec is generally going to be faster than VecDeque, and VecDeque is generally going to be faster than LinkedList"1. For Java's
ArrayList, "The constant factor is low compared to that for the LinkedList implementation"13. When speed matters, measure with real data. - Expected and amortized costs are averages. A hash map is O(1) only on average. Rust says that "It is theoretically possible, though very unlikely, for HashMap to experience significantly worse performance than the expected cost"1, and the .NET table gives O(n) as the worst case for
HashSet<T>.Add5. An add at the end of an array list is O(1) amortized, but one add can copy the whole array when the list grows1. - Order is not the same in every language. A Python
dictkeeps the order in which the keys were added: "Dictionaries preserve insertion order"14. A JavaScriptMapalso iterates "in insertion order"12. In Go, "The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next"9. Do not depend on the order of a hash map unless the language guarantees it. - Other needs change the choice. Code that more than one thread uses, or code that must not change a collection, needs other types. The .NET table has a separate column for thread-safe and immutable collections, and says that "Often immutable collection types are less performant but provide immutability"5.
- A sorted map is not the only way to get order. When the code sorts only once, at the end, a hash map and one sort can be enough. The Python, JavaScript and Go examples do this.
References
- Module std::collections, Rust standard library, When Should You Use Which Collection?; Performance
- Collections Framework Overview, Java SE 21, Collection Implementations
- Containers library, C++ reference, cppreference.com, Sequence containers; Associative containers; Unordered associative containers
- Data Structures, The Python Tutorial, 5.1.2 Using Lists as Queues; 5.4 Sets
- Collections and Data Structures, .NET documentation, Choose a collection; Algorithmic complexity of collections
- collections, Python 3.14 documentation, deque objects
- ArrayDeque, Java SE 21 API, Class description
- SortedDictionary<TKey,TValue> Class, .NET API reference, Remarks
- The Go Programming Language Specification, Map types; For statements with range clause
- Effective Go, Maps
- container/list, Go standard library, Overview
- Keyed collections, MDN Web Docs, Map object; Object and Map compared; Set object
- ArrayList, Java SE 21 API, Class description
- Built-in Types, Python 3.14 documentation, Mapping Types, dict
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag XYNGGR Edit this page History Report an error Markdown