Skip to content

Lists, sets and maps ​

KeysOrderDuplicatesTypical use
ImmutableList<T>0..n-1insertionallowedmost domain collections
ImmutableSet<T>nonefirst appearanceignoredtags, permissions, ids
ImmutableMap<K, V>any type, exactinsertionone value per keyindexes, lookups, totals

Lists ​

php
$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 ​

php
$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 ​

php
$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));        // false

Keys 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):

php
$builder = Users::builder();

foreach ($rows as $row) {
    $builder->add(User::fromRow($row));
}

$users = $builder->build(); // Users, invariants checked once
5000 elements, PHP 8.3time
append() in a loop35 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 and unserialize() 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.