Howard Lovatt howard.lovatt at
Tue Mar 12 19:26:24 PDT 2013


I have found the Collector interface and its primitive siblings really
useful with streams. However I have wanted to add a feature where it works
optionally with an intermediate type and then converts to the result type.

interface Collector<T, I, R> {
  boolean isConcurrent();

  Supplier<I> intermediateSupplier();

  BiConsumer<I, T> accumulator();

  BinaryOperator<I> combiner();

  R resultConverter(I intermediateResult);

The reasons that I have wanted an intermediate type fall into
two categories: for efficiency and/or for convenience of programming. For
example it would be great to add a collector that made a
string representation of a stream. EG assuming stream contains 1, 2, 3:


gives the string

  "[1, 2, 3]"

Note the output is a String and it is surrounded by square brackets.
Assuming that the intermediate type was a StringBuilder, the result
converter function would be:

  String resultConverter(final StringBuilder intermediateResult) {
    intermediateResult.insert(0, '[');
    return intermediateResult.toString();

The above example demonstrated both efficiency, StringBuilder is more
efficient than String, and convenience, it is easier to add the '[]' at the

Is this something others have wanted?

  -- Howard.

More information about the lambda-dev mailing list