Programming Search⌘K

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))
Output
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

LanguageVerdictNote
PythonNative
C++Standard library
JavaStandard library
CIdiom
C#Standard library
JavaScriptNative
TypeScriptNative
GoNative
RustStandard library
KotlinStandard libraryThe 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.
SQLDoes not applyA table holds rows, but SQL has no collection values in program code.
BashNative
PowerShellNativePowerShell has arrays and hash tables in the language, and it can use the .NET collections. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML has no collection values.
CSSDoes not applyCSS has no collection values.
Regular expressionsDoes not applyA 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.

PythonGitHub
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"])
Output
list 4 True True
set 3 True True
Counter 3 True True
blue ['blue', 'green', 'red'] 2
  • Verdict: native. list, set and dict are built-in types with a literal syntax. The collections module adds more, such as Counter, deque and defaultdict.
  • A Counter is a dict subclass, so len counts its keys and in tests a key.
  • Each of the three is a collections.abc.Collection: it has len, iteration and the in test.
#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';
}
Output
4 blue
3 1
blue=1 green=1 red=2
  • Verdict: stdlib. The containers library has sequence containers such as std::vector and std::list, associative containers such as std::set and std::map, and unordered containers such as std::unordered_map.
  • counts[w] adds the key with the value 0 when the key is not there, so ++counts[w] counts each word.
  • std::set and std::map keep their keys sorted. contains returns a bool, which std::cout prints as 1.
JavaGitHub
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);
    }
}
Output
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.util has the interfaces List, Set and Map and classes that implement them.
  • describe takes any Collection<String>, so it works for the list and the set.
  • A Map is not a Collection. The code passes counts.keySet(), a view of the keys that is a collection.
  • TreeSet and TreeMap keep 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;
}
Output
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 malloc and realloc.
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"]}");
Output
List`1 4 True
SortedSet`1 3 True
KeyCollection 3 True
blue blue,green,red 2
  • Verdict: stdlib. System.Collections.Generic has List<T>, HashSet<T>, SortedSet<T>, Dictionary<TKey,TValue> and SortedDictionary<TKey,TValue>.
  • Describe takes any ICollection<T>. The keys of a dictionary are an ICollection<TKey> too.
  • The name of a generic class has a backtick and the number of its type parameters, as in List`1.
JavaScriptGitHub
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()]);
Output
4 blue true
3 true [ 'red', 'blue', 'green' ]
3 2 [ 'red', 'blue', 'green' ]
  • Verdict: native. Array, Set and Map are built-in objects. An array has a literal syntax; a set and a map are made with new.
  • A Set and a Map give 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 is size.
TypeScriptGitHub
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"));
Output
4 3 3
blue true 2
  • Verdict: native. TypeScript uses the JavaScript collections and gives them item types, such as string[], Set<string> and Map<string, number>.
  • The checker rejects a call such as counts.set("red", "two"), because the values must be numbers.
  • The function size shows a difference between the kinds: an array has length, and a set or a map has size.
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)))
}
Output
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/heap and container/ring have other collections.
RustGitHub
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);
}
Output
4 blue true
3 true {"blue", "green", "red"}
3 2 {"blue": 1, "green": 1, "red": 2}
  • Verdict: stdlib. Vec is in the prelude, and std::collections has VecDeque, LinkedList, HashMap, BTreeMap, HashSet, BTreeSet and BinaryHeap.
  • collect builds any collection from an iterator. The type of unique says which one.
  • BTreeSet and BTreeMap keep their keys sorted. A HashSet or a HashMap gives its keys in an order that is not fixed.
BashGitHub
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 ' '
Output
4 blue
3 2
blue=1 green=1 red=2
  • Verdict: native. Bash has indexed arrays and associative arrays. The elements are strings.
  • declare -A makes 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.
  • 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 ConcurrentHashMap in Java and System.Collections.Concurrent in .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 Map cannot go where the code expects a Collection. Use keySet(), values() or entrySet() 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 add on an unmodifiable list throws UnsupportedOperationException when 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

  1. Collections Framework Overview, Java SE 21, Introduction; Collection Interfaces; Collection Implementations; Design Goals
  2. Collections overview, Kotlin documentation, Whole page
  3. Collection (abstract data type), Wikipedia, Introduction; Subtypes; Implementation
  4. Module std::collections, Rust standard library, Introduction; Performance
  5. Collections and Data Structures, .NET documentation, Introduction; Common collection features
  6. collections.abc, Python 3.14 documentation, class collections.abc.Collection
  7. Containers library, C++ reference, cppreference.com, Introduction
  8. The Go Programming Language Specification, Map types; For statements with range clause
  9. Keyed collections, MDN Web Docs, Introduction
  10. Arrays, Bash Reference Manual, 6.7 Arrays
  11. Built-in Types, Python 3.14 documentation, Sequence Types; Set Types; Mapping Types
  12. Standard Template Library, Wikipedia, History
  13. 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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/KEJMDR/text.yaml