Class Collector

java.lang.Object
eu.bandm.tools.util.java.Collector

public abstract class Collector extends Object
Find one or more results of a construction.

Constructions are not represented as function objects of type Supplier<R> but rather, by double inversion of control, as objects of type Consumer<Consumer<R>>. They are invoked with a temporary functional object of type Consumer<R> that acts as a sink for results. The sink objects becomes invalid after the results of a single construction have been collected; no reference to it should escape.

For example, a construction that yields all elements of a given list could be represented as sink -> { for(R elem : list) sink.accept(r);}, or more concisely as list::forEach.

Sink objects do not accept null results; a NullPointerException will be thrown.

  • Method Details

    • findFirstResult

      public static <R> Optional<R> findFirstResult(Consumer<Consumer<R>> construction)
      Find the first result of the given construction.

      The construction is aborted, by means of exception handling, immediately after yielding the first result. Any necessary cleanup operations must be done in finally blocks.

      Type Parameters:
      R - the type of results
      Parameters:
      construction - the construction
      Returns:
      the first result yielded by the construction wrapped in Optional.of, or Optional.empty() if there is none
    • findUniqueResult

      public static <R> Optional<R> findUniqueResult(Consumer<Consumer<R>> construction) throws Collector.NonUniqueException
      Find the unique result of the given construction.
      Type Parameters:
      R - the type of results
      Parameters:
      construction - the construction
      Returns:
      the first and only result yielded by the construction wrapped in Optional.of, or Optional.empty() if there is none
      Throws:
      Collector.NonUniqueException - if there is more than one result
    • findAllResults

      public static <R> List<R> findAllResults(Consumer<Consumer<R>> construction)
      Find all results of the given construction.
      Type Parameters:
      R - the type of results
      Parameters:
      construction - the construction
      Returns:
      a list of all results, in the order they have been yielded