Java 8 comes with streaming API, it divides data processing into two phases: intermediate operations and terminal operation.Terminal operation can have few different forms and I would like to concentrate on reduction to collections, especially to Guava immutable collections. Terminal operation requires collector which will collect data and return it as required structure, but Guava does not provide such collector. In order to create Guava collection out of a stream we have to first reduce stream result into temporary collection and than transfer it:
Reduction of our stream stores results in a temporary List (Collectors.toList()). Once stream processing is done the finisher function will convert content of this List into Guava collection (ImmutableSortedSet::copyOf).
The problem with this approach is… that we have this extra converting loop and two arrays in memory (List and Builder). This could be avoided it we would have collector that is based on Guava’s Builder. So…. I’ve implemented one, once we use it, the code above can be simplified into such form:
The code is straight forward, let’s concentrate on implementation of #toNaturalImmutableSortedSet()
Our collector is being created by factory method Collector#of that takes four arguments:
Based on this pattern we can implement other collectors:
In case you’ve become curious and would like to discover which potential for innovative software solutions your company holds, get to know us: either in a first conversation, an individually crafted workshop or at one of our numerous community events!