Collector

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


Hi,

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.
IE

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:

  stream.collect(toString)

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, '[');
    intermediateResult.append(']');
    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
end.

Is this something others have wanted?

  -- Howard.


More information about the lambda-dev mailing list