Lists, sets and maps
| Keys | Order | Duplicates | Typical use | |
|---|---|---|---|---|
ImmutableList<T> | 0..n-1 | insertion | allowed | most domain collections |
ImmutableSet<T> | none | first appearance | ignored | tags, permissions, ids |
ImmutableMap<K, V> | any type, exact | insertion | one value per key | indexes, lookups, totals |
Lists
$users->get(0); // User, or ElementNotFound
$users->getOrNull(10); // User|null
$users->sortBy(fn(User $u) => $u->name)->take(10);
$users->groupBy(fn(User $u) => $u->team); // ImmutableMap<string, Users>
$users->keyBy(fn(User $u) => $u->id); // ImmutableMap<UserId, User>
[$active, $blocked] = $users->partition(fn(User $u) => $u->isActive());sort() and sortBy() use natural order (<=>) only where it means something: scalars, null, dates and arrays of them. For enums and other objects they throw NotComparable; sort by a scalar key instead, sortBy(fn(Status $s) => $s->value), or pass a comparator to sortWith().
Sets
$tags = Tags::of(new Tag('php'), new Tag('ddd'), new Tag('php')); // 2 tags
$tags->contains(new Tag('php')); // O(1)
$tags->union($other)->intersect($allowed)->diff($banned);Elements must be hashable: scalars, null or objects, not arrays.
Maps
$byId = UsersById::fromPairs([[new UserId(1), $alice]]);
$byId->get(new UserId(1)); // $alice: UserId implements Hashable
$byId->with(new UserId(2), $bob); // a new map
$byId->has(new UserId(3)); // falseKeys keep their exact type: "1", 1, 1.0 and true are four different keys, and an object can be a key. toArray() and json_encode() throw UnsupportedKey when a key cannot become a PHP array key.
Building in a loop
Every operation copies, so append() in a loop costs O(n²). A builder checks each element once and builds in O(n):
$builder = Users::builder();
foreach ($rows as $row) {
$builder->add(User::fromRow($row));
}
$users = $builder->build(); // Users, invariants checked once| 5000 elements, PHP 8.3 | time |
|---|---|
append() in a loop | 35 ms |
builder()->add() + build() | 1.5 ms |
Map builders have put(), putAll() and putMerged($key, $value, $combine), which combines a value with the one already under the key.
What is checked when
- Entering: factories,
append(),with(), builders andunserialize()check each new element. - Rearranging:
filter(),sort(),slice(),reverse()check nothing: the elements were checked when they entered. - Always: invariants run for every new instance.
The full method list is in the reference.