Conceptintro
Collection
Also called container, collection type, collections library, collections framework, sequence, set, map.
A collection is a value that holds other values, its elements. The main kinds are sequences such as lists, sets of unique elements, and maps from keys to values.
- Applies to
- core-languages
Idea
Programs seldom work on one value at a time. They keep the lines of a file, the users who are logged in, or the price of each product. A collection is a value that holds other values, called its elements. The program can add elements, remove them, look for one, count them and go through them one by one.
Most languages have three main kinds of collection. A sequence keeps its elements in an order, and the program gets each one by its position. A set keeps each element at most once. A map keeps pairs of a key and a value, and the program gets a value by its key.
words = ["red", "blue", "red", "green"] # a sequence: order and duplicates
unique = set(words) # a set: each element once
counts = {} # a map: key to value
for w in words:
counts[w] = counts.get(w, 0) + 1
print(len(words), words[1])
print(len(unique), "red" in unique)
print(counts["red"], sorted(counts))
4 blue
3 True
2 ['blue', 'green', 'red']
The list keeps all four words in order. The set keeps three, because it drops the second "red". The map counts each word. All three collections support len, the in test and a loop, but each one answers a different question fast.
How it works
A group of elements. In the Java documentation, "A collection is an object that represents a group of objects"1. Kotlin uses the same words: "Objects in a collection are called elements or items"2. In theory, a collection is "a grouping of items that can be used in a polymorphic way"3: code that counts the elements or goes through them works for every kind of collection.
The main kinds. Wikipedia divides collections into linear and associative kinds. A linear collection keeps an order, and "Some collections are interpreted as a sort of function: given an input, the collection yields an output"3. Kotlin names three main types. "List is an ordered collection"2; "Set is a collection of unique elements"2; and a "Map (or dictionary) is a set of key-value pairs"2. Rust puts its standard collections into four groups: sequences (Vec, VecDeque, LinkedList), maps (HashMap, BTreeMap), sets (HashSet, BTreeSet) and one other, BinaryHeap4. Stacks, queues and priority queues are linear collections with a fixed rule for which element comes out next. See list, set and map.
The common operations. In .NET, "All collections provide methods for adding, removing, or finding items in the collection"5. Nearly all collections also know their size and can give their elements one at a time. Python names this common part: Collection is the "ABC for sized iterable container classes"6, so a collection has len, a loop and the in test. A program that uses only these operations works with any collection. See iterators and collection interfaces.
The kind is not the storage. A collection says what the program can do with its elements. A data structure says how the elements are stored. One kind can have many data structures: "a priority queue is often implemented as a heap, while an associative array is often implemented as a hash table"3. The collection is an abstract data type, and each library class is one implementation of it.
Collection libraries. Each language puts its collections in a library, or builds some of them into the language. Java has "a unified architecture for representing and manipulating collections"1 in java.util. In C++, "The Containers library is a generic collection of class templates and algorithms that allow programmers to easily implement common data structures like queues, lists and stacks"7. Go builds slices and maps into the language: "A map is an unordered group of elements of one type, called the element type, indexed by a set of unique keys of another type, called the key type"8. JavaScript has arrays and the keyed collections, where "Map and Set objects contain elements which are iterable in the order of insertion"9. "Bash provides one-dimensional indexed and associative array variables"10.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Standard library | |
| Java | Standard library | |
| C | Idiom | |
| C# | Standard library | |
| JavaScript | Native | |
| TypeScript | Native | |
| Go | Native | |
| Rust | Standard library | |
| Kotlin | Standard library | The kotlin.collections package has List, Set and Map, with a read-only and a mutable interface for each. No example file exists because kotlinc is not installed. |
| SQL | Does not apply | A table holds rows, but SQL has no collection values in program code. |
| Bash | Native | |
| PowerShell | Native | PowerShell has arrays and hash tables in the language, and it can use the .NET collections. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML has no collection values. |
| CSS | Does not apply | CSS has no collection values. |
| Regular expressions | Does not apply | A regular expression does not hold values. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | built-in list, tuple, set, dict; more in collections; collections.abc for the interfaces |
| JavaScript | native | Array, Map, Set, typed arrays; WeakMap and WeakSet |
| TypeScript | native | the JavaScript collections with item types, such as string[] and Map<string, number> |
| Java | stdlib | the collections framework in java.util: List, Set, Map, Queue, Deque; arrays are separate |
| Kotlin | stdlib | List, Set, Map and their mutable forms in kotlin.collections |
| C# | stdlib | System.Collections.Generic: List<T>, HashSet<T>, Dictionary<TKey,TValue>, Queue<T> |
| Go | native | built-in arrays, slices and maps; container/list, container/heap and container/ring in the library |
| Rust | stdlib | std::collections: Vec, VecDeque, HashMap, BTreeMap, HashSet, BinaryHeap |
| C | idiom | built-in fixed arrays; the program writes other collections with structs and pointers |
| C++ | stdlib | the containers library: std::vector, std::list, std::set, std::map, std::unordered_map |
| Bash | native | indexed arrays and associative arrays of strings |
| PowerShell | native | arrays and hash tables, and the .NET collections |
| SQL | n/a | a table holds rows, but SQL has no collection values in program code |
| Regex | n/a | a pattern does not hold values |
| HTML | n/a | HTML has no collection values |
| CSS | n/a | CSS has no collection values |
Python, JavaScript, Go and Bash build their main collections into the language, with a literal syntax for each. Java, C#, Rust and C++ put them in the standard library, as generic types. C has only fixed arrays, so a C program writes its own list or map, or uses a library.
The example files do the same work in each language: keep a list of words, make a set of the unique words, and count each word in a map. Python uses list, set and dict. JavaScript and TypeScript use Array, Set and Map. Java uses ArrayList, TreeSet and TreeMap. C# uses List<T>, SortedSet<T> and SortedDictionary<TKey,TValue>. Go uses a slice and a map, and sorts the keys to print them. Rust uses Vec, BTreeSet and BTreeMap. C uses an array and a small table that it searches by hand. C++ uses std::vector, std::set and std::map. Bash uses an indexed array and an associative array.
from collections import Counter
from collections.abc import Collection
words = ["red", "blue", "red", "green"]
unique = set(words)
counts = Counter(words)
for c in (words, unique, counts):
print(type(c).__name__, len(c), "red" in c, isinstance(c, Collection))
print(words[1], sorted(unique), counts["red"])
list 4 True True
set 3 True True
Counter 3 True True
blue ['blue', 'green', 'red'] 2
- Verdict: native.
list,setanddictare built-in types with a literal syntax. Thecollectionsmodule adds more, such asCounter,dequeanddefaultdict. - A
Counteris adictsubclass, solencounts its keys andintests a key. - Each of the three is a
collections.abc.Collection: it haslen, iteration and theintest.
#include <iostream>
#include <map>
#include <set>
#include <string>
#include <vector>
int main() {
std::vector<std::string> words{"red", "blue", "red", "green"};
std::set<std::string> unique(words.begin(), words.end());
std::map<std::string, int> counts;
for (const auto& w : words) {
++counts[w];
}
std::cout << words.size() << ' ' << words[1] << '\n';
std::cout << unique.size() << ' ' << unique.contains("red") << '\n';
const char* sep = "";
for (const auto& [word, n] : counts) {
std::cout << sep << word << '=' << n;
sep = " ";
}
std::cout << '\n';
}
4 blue
3 1
blue=1 green=1 red=2
- Verdict: stdlib. The containers library has sequence containers such as
std::vectorandstd::list, associative containers such asstd::setandstd::map, and unordered containers such asstd::unordered_map. counts[w]adds the key with the value 0 when the key is not there, so++counts[w]counts each word.std::setandstd::mapkeep their keys sorted.containsreturns abool, whichstd::coutprints as1.
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;
public class Main {
static String describe(Collection<String> c) {
return c.getClass().getSimpleName() + " " + c.size() + " " + c.contains("red");
}
public static void main(String[] args) {
List<String> words = new ArrayList<>(List.of("red", "blue", "red", "green"));
TreeSet<String> unique = new TreeSet<>(words);
Map<String, Integer> counts = new TreeMap<>();
for (String w : words) {
counts.merge(w, 1, Integer::sum);
}
System.out.println(describe(words));
System.out.println(describe(unique));
System.out.println(describe(counts.keySet()) + " " + counts);
System.out.println(words.get(1) + " " + unique);
}
}
ArrayList 4 true
TreeSet 3 true
KeySet 3 true {blue=1, green=1, red=2}
blue [blue, green, red]
- Verdict: stdlib. The collections framework in
java.utilhas the interfacesList,SetandMapand classes that implement them. describetakes anyCollection<String>, so it works for the list and the set.- A
Mapis not aCollection. The code passescounts.keySet(), a view of the keys that is a collection. TreeSetandTreeMapkeep their elements sorted, so the output order is fixed.
#include <stdio.h>
#include <string.h>
struct count {
const char *word;
int n;
};
/* Find word in the table, or add it. Return its entry. */
static struct count *lookup(struct count *table, size_t *len, const char *word) {
for (size_t i = 0; i < *len; i++) {
if (strcmp(table[i].word, word) == 0) {
return &table[i];
}
}
table[*len].word = word;
table[*len].n = 0;
return &table[(*len)++];
}
int main(void) {
const char *words[] = {"red", "blue", "red", "green"};
size_t nwords = sizeof words / sizeof words[0];
struct count table[4];
size_t len = 0;
for (size_t i = 0; i < nwords; i++) {
lookup(table, &len, words[i])->n++;
}
printf("%zu %s\n", nwords, words[1]);
printf("%zu", len);
for (size_t i = 0; i < len; i++) {
printf(" %s=%d", table[i].word, table[i].n);
}
printf("\n");
return 0;
}
4 blue
3 red=2 blue=1 green=1
- Verdict: idiom. C has fixed arrays and structs. The program writes its own collections, or uses a library.
- The table is an array of structs that the code searches from the start, so each lookup takes time in proportion to the number of words. A real program would use a hash table.
- The size of the array is fixed when the program is compiled. A collection that grows needs
mallocandrealloc.
using System;
using System.Collections.Generic;
var words = new List<string> { "red", "blue", "red", "green" };
var unique = new SortedSet<string>(words);
var counts = new SortedDictionary<string, int>();
foreach (var w in words)
{
counts[w] = counts.GetValueOrDefault(w) + 1;
}
static string Describe<T>(ICollection<T> c, T item) => $"{c.GetType().Name} {c.Count} {c.Contains(item)}";
Console.WriteLine(Describe(words, "red"));
Console.WriteLine(Describe(unique, "red"));
Console.WriteLine(Describe(counts.Keys, "red"));
Console.WriteLine($"{words[1]} {string.Join(",", unique)} {counts["red"]}");
List`1 4 True
SortedSet`1 3 True
KeyCollection 3 True
blue blue,green,red 2
- Verdict: stdlib.
System.Collections.GenerichasList<T>,HashSet<T>,SortedSet<T>,Dictionary<TKey,TValue>andSortedDictionary<TKey,TValue>. Describetakes anyICollection<T>. The keys of a dictionary are anICollection<TKey>too.- The name of a generic class has a backtick and the number of its type parameters, as in
List`1.
const words = ["red", "blue", "red", "green"];
const unique = new Set(words);
const counts = new Map();
for (const w of words) {
counts.set(w, (counts.get(w) ?? 0) + 1);
}
console.log(words.length, words[1], words.includes("red"));
console.log(unique.size, unique.has("red"), [...unique]);
console.log(counts.size, counts.get("red"), [...counts.keys()]);
4 blue true
3 true [ 'red', 'blue', 'green' ]
3 2 [ 'red', 'blue', 'green' ]
- Verdict: native.
Array,SetandMapare built-in objects. An array has a literal syntax; a set and a map are made withnew. - A
Setand aMapgive their elements in the order of insertion, so the output order is fixed. - The size of an array is
length, and the size of a set or a map issize.
const words: string[] = ["red", "blue", "red", "green"];
const unique: Set<string> = new Set(words);
const counts: Map<string, number> = new Map();
for (const w of words) {
counts.set(w, (counts.get(w) ?? 0) + 1);
}
function size(c: { length: number } | { size: number }): number {
return "length" in c ? c.length : c.size;
}
console.log(size(words), size(unique), size(counts));
console.log(words[1], unique.has("red"), counts.get("red"));
4 3 3
blue true 2
- Verdict: native. TypeScript uses the JavaScript collections and gives them item types, such as
string[],Set<string>andMap<string, number>. - The checker rejects a call such as
counts.set("red", "two"), because the values must be numbers. - The function
sizeshows a difference between the kinds: an array haslength, and a set or a map hassize.
package main
import (
"fmt"
"maps"
"slices"
)
func main() {
words := []string{"red", "blue", "red", "green"}
unique := map[string]struct{}{}
counts := map[string]int{}
for _, w := range words {
unique[w] = struct{}{}
counts[w]++
}
_, hasRed := unique["red"]
fmt.Println(len(words), words[1], slices.Contains(words, "red"))
fmt.Println(len(unique), hasRed)
fmt.Println(len(counts), counts["red"], slices.Sorted(maps.Keys(counts)))
}
4 blue true
3 true
3 2 [blue green red]
- Verdict: native. Arrays, slices and maps are built into the language. Go has no set type, so the code uses a map with empty values as a set.
- The order of a loop over a map is not fixed, so the code sorts the keys before it prints them.
- The packages
container/list,container/heapandcontainer/ringhave other collections.
use std::collections::{BTreeMap, BTreeSet};
fn main() {
let words = vec!["red", "blue", "red", "green"];
let unique: BTreeSet<&str> = words.iter().copied().collect();
let mut counts: BTreeMap<&str, usize> = BTreeMap::new();
for w in &words {
*counts.entry(w).or_insert(0) += 1;
}
println!("{} {} {}", words.len(), words[1], words.contains(&"red"));
println!("{} {} {:?}", unique.len(), unique.contains("red"), unique);
println!("{} {} {:?}", counts.len(), counts["red"], counts);
}
4 blue true
3 true {"blue", "green", "red"}
3 2 {"blue": 1, "green": 1, "red": 2}
- Verdict: stdlib.
Vecis in the prelude, andstd::collectionshasVecDeque,LinkedList,HashMap,BTreeMap,HashSet,BTreeSetandBinaryHeap. collectbuilds any collection from an iterator. The type ofuniquesays which one.BTreeSetandBTreeMapkeep their keys sorted. AHashSetor aHashMapgives its keys in an order that is not fixed.
words=(red blue red green)
declare -A counts
for w in "${words[@]}"; do
counts[$w]=$(( ${counts[$w]:-0} + 1 ))
done
echo "${#words[@]} ${words[1]}"
echo "${#counts[@]} ${counts[red]}"
for k in "${!counts[@]}"; do
echo "$k=${counts[$k]}"
done | sort | paste -sd ' '
4 blue
3 2
blue=1 green=1 red=2
- Verdict: native. Bash has indexed arrays and associative arrays. The elements are strings.
declare -Amakes an associative array. Bash has no set type, so the keys of an associative array act as a set.- The order of the keys of an associative array is not fixed, so the code sorts them.
Variations and related ideas
- Mutable and read-only. "Each main collection type has a read-only interface, such as List, and a corresponding mutable interface, such as MutableList"2 in Kotlin. Java uses the terms unmodifiable and immutable: "Collections that do not support modification operations (such as add, remove and clear) are referred to as unmodifiable"1. See immutability.
- Generic and non-generic. An older library stores elements of the most general type. In .NET, "Non-generic collections store items as Object, require casting"5. Generic collections take the element type as a parameter. See generic containers.
- Arrays. In some languages the array is not one of the library collections. In Kotlin, "Arrays aren't a type of collection"2. Java arrays "cannot be made to implement the Collection interface directly without changing the language"1, so the framework has methods to change one into the other. See array.
- Concurrent collections. Some libraries have collections that many threads can use at once, such as
ConcurrentHashMapin Java andSystem.Collections.Concurrentin .NET15.
Pitfalls
- Order that is not part of the contract. A set or a hash map may give its elements in any order. In Go, "The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next"8. Python dicts keep the order in which keys were added: "Dictionaries preserve insertion order"11. A Python set has no order: it is "an unordered collection of distinct hashable objects"11. Sort the elements, or use an ordered collection, when the output must be in an order.
- A map is not always a collection. In Java, the map interfaces "are not true collections"1, so a
Mapcannot go where the code expects aCollection. UsekeySet(),values()orentrySet()to get a collection view. - Operations that are not supported. In Java, "Many of the modification methods in the collection interfaces are labeled optional"1. A call to
addon an unmodifiable list throwsUnsupportedOperationExceptionwhen the program runs. - Changing a collection during a loop. A loop that adds or removes elements of the collection that it goes through can skip elements or fail. The general-purpose Java collections "have fail-fast iterators, which detect invalid concurrent modification"1. Collect the changes in a second collection, or loop over a copy.
- The name of the implementation. Programmers often call a priority queue a heap and a map a hash, but "this is incorrect conceptually"3. Choose the kind of collection by what the program does with it, and then choose the implementation by its cost.
Cost
Each kind of collection makes some operations fast and others slow. The Rust documentation gives a table: getting the element at an index is O(1) for a Vec and O(min(i, n-i)) for a LinkedList, and a lookup in a BTreeMap is O(log(n))4. A collection that grows must sometimes move its elements. In .NET, "if Count is less than Capacity, adding an item is an O(1) operation"5; when the capacity must grow, "The memory is reallocated, and the elements are copied from the old collection to the new one"5. See choose a collection.
History
The C++ containers come from the Standard Template Library (STL). "In November 1993 Alexander Stepanov presented a library based on generic programming to the ANSI/ISO committee for C++ standardization"12, and "A proposal received final approval at the July 1994 ANSI/ISO committee meeting"12. In Java, "The collections framework was designed and developed primarily by Joshua Bloch, and was introduced in JDK 1.2"13. The older classes Vector and Hashtable "were retrofitted to implement the collection interfaces"1.
References
- Collections Framework Overview, Java SE 21, Introduction; Collection Interfaces; Collection Implementations; Design Goals
- Collections overview, Kotlin documentation, Whole page
- Collection (abstract data type), Wikipedia, Introduction; Subtypes; Implementation
- Module std::collections, Rust standard library, Introduction; Performance
- Collections and Data Structures, .NET documentation, Introduction; Common collection features
- collections.abc, Python 3.14 documentation, class collections.abc.Collection
- Containers library, C++ reference, cppreference.com, Introduction
- The Go Programming Language Specification, Map types; For statements with range clause
- Keyed collections, MDN Web Docs, Introduction
- Arrays, Bash Reference Manual, 6.7 Arrays
- Built-in Types, Python 3.14 documentation, Sequence Types; Set Types; Mapping Types
- Standard Template Library, Wikipedia, History
- Java collections framework, Wikipedia, History
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 | W4 complete |
|
Tag KEJMDR Edit this page History Report an error Markdown