Identity Finish in Java Collectors
Definition
In Java's Stream API, the IDENTITY_FINISH characteristic is a property of a Collector. It indicates that the finisher function of the collector is the identity function, meaning that the result container can be directly used as the final result without any additional transformation. This characteristic allows for certain optimizations, as the finisher step can be effectively ignored.
Example Usage
To illustrate the use of IDENTITY_FINISH, consider the following example of a custom Collector designed to fold a Stream<String> into a List<List<String>>. This collector simulates the grouping of words into lines, each with a maximum length. The example demonstrates how to define a generic GroupingCollector that utilizes the IDENTITY_FINISH characteristic.
import java.util.ArrayList;
import java.util.List;
import java.util.function.*;
import java.util.stream.Collector;
import static java.util.stream.Collector.Characteristics.IDENTITY_FINISH;
public class GroupingCollector<T> {
private final BiPredicate<List<T>, T> p;
public GroupingCollector(BiPredicate<List<T>, T> p) {
this.p = p;
}
public void accumulator(List<List<T>> llt, T t) {
if (! llt.isEmpty()) {
List<T> last = llt.get(llt.size() - 1);
if (p.test(last, t)) {
llt.get(llt.size() - 1).add(t);
} else {
addNewList(llt, t);
}
} else {
addNewList(llt, t);
}
}
public List<List<T>> combiner(List<List<T>> list1, List<List<T>> list2) {
List<List<T>> result = new ArrayList<>();
result.addAll(list1);
result.addAll(list2);
return result;
}
public static <T> void addNewList(List<List<T>> llt, T t) {
List<T> list = new ArrayList<>();
list.add(t);
llt.add(list);
}
public Collector<T, List<List<T>>, List<List<T>>> collector() {
return Collector.of(ArrayList::new, this::accumulator, this::combiner, IDENTITY_FINISH);
}
}
Explanation
-
Accumulator: The
accumulatormethod is responsible for adding elements to the current list. If the last list in the collection can accommodate the new element (as determined by the predicatep), the element is added to that list. Otherwise, a new list is created and added to the collection. -
Combiner: The
combinermethod merges two lists of lists into one. This is useful for parallel processing where partial results need to be combined. -
Collector: The
collectormethod constructs theCollectorusing theIDENTITY_FINISHcharacteristic. This indicates that the result of the collection process is already in the desired final form, and no additional finishing step is required.
This example demonstrates how the IDENTITY_FINISH characteristic can simplify the implementation of a collector by eliminating the need for a separate finisher function, thus making the collector more efficient and straightforward.
FAQ (Frequently asked questions)
What is IDENTITY_FINISH in Java 8 functional programming?
What does it mean when a Collector has the IDENTITY_FINISH characteristic?