A data addition operation replaces in-place mutation with a binary operation that combines two values and returns a new value. The result stays within the same data shape, making the hidden algebra of ordinary collection code explicit. section 7.3
Apply the idea by making the operation closed and defining its domain-specific behavior:
- Add lists by concatenating their contents into a new list. section 7.3
- Add maps by copying entries, then choose how colliding keys combine or which value wins. section 7.3
- Parameterize map addition with a BinaryOperator when values need their own combination rule. section 7.3
Grouping through addition
A groupBy function can map each item to a one-entry map, then reduce those maps with map addition. Duplicate keys combine their lists through list addition, replacing mutable accumulation with explicit data transformations. section 7.3
Listing 7.8 Adding two lists as a binary operation
static <T> List<T> add(List<T> list1, List<T> list2) { #A
return Stream.concat(list1.stream(), list2.stream()).toList(); #A
}
static <T> List<T> add(List<T> list1, List<T> list2) { #B
List<T> output = new ArrayList(list1);
output.addAll(list2); #C
return List.copyOf(output);
}Inspect the Java implementations that add two lists by concatenating or copying contents before returning an immutable result. section 7.3
