Type-safe maps
Inspired by the heterogeneous map pattern described in Effective Java by Joshua Bloch,
TypeSafeMap
is an immutable map that works with type-aware keys, so its retrieval method is type-safe; furthermore it supports Optional
.
final Key<String> k1 = Key.of("Key 1", String.class);
final Key<Integer> k2 = Key.of("Key 2", Integer.class);
final var m = TypeSafeMap.newInstance()
.with(k1, "Value 1")
.with(k2, 1);
final Optional<String> v1 = m.getOptional(k1);
final Optional<Integer> v2 = m.getOptional(k2);
assertThat(v1).contains("Value 1");
assertThat(v2).contains(1);
TypeSafeMultiMap
is similar, but associates keys to collection of values, not single values; so associating multiple (key, value)
pairs keep
all the values instead of replacing the previous one.
final Key<String> k1 = Key.of("Key 1", String.class);
final Key<Integer> k2 = Key.of("Key 2", Integer.class);
final var m = TypeSafeMultiMap.newInstance()
.with(k1, "Value 1")
.with(k1, "Value 2")
.with(k2, 1)
.with(k2, 2);
final Collection<String> v1 = m.get(k1);
final Collection<Integer> v2 = m.get(k2);
assertThat(v1).containsExactly("Value 1", "Value 2");
assertThat(v2).containsExactly(1, 2);
Find more information in the JavaDoc for TypeSafeMap and TypeSafeMultiMap.