The HashMap class is an implementation of the Map<TK, TV> interface, providing efficient key-value storage. It supports storing objects as keys.
By default, when using objects as keys, HashMap compares them using the spl_object_hash function. This means comparison is based on object identity rather than object state.
To use objects as keys based on their internal state (value equality) rather than identity, your class must implement the HashContract interface and define equals(mixed $that): bool and hashCode(): string methods.
<?php
declare(strict_types=1);
use Fp\Collections\HashMap;
// To use objects as keys based on value equality, implement HashContract
final class Foo implements HashContract
{
public function __construct(
public readonly int $a,
public readonly bool $b = true,
) {}
public function equals(mixed $that): bool
{
return $that instanceof self
&& $this->a === $that->a
&& $this->b === $that->b;
}
public function hashCode(): string
{
return md5(implode(',', [$this->a, $this->b]));
}
}
// Creating a HashMap from pairs
$collection = HashMap::collectPairs([
[new Foo(1), 1],
[new Foo(2), 2],
[new Foo(3), 3],
[new Foo(4), 4]
]);
// Retrieving a value by key with a fallback
$value = $collection(new Foo(2))->getOrElse(0); // 2
// Performing functional operations
$result = $collection
->map(fn(int $value) => $value + 1)
->filter(fn(int $value) => $value > 2)
->fold(0)(fn(int $acc, int $value) => $acc + $value); // 12