-1

So, the question is pretty self-explanatory: is there a way to create a Collector, that is collecting stream that is passed to it into a new stream?

I am aware that it can be done with some tricks like:

Collectors.collectingAndThen(Collectors.toList(), List::stream);

But this code allocates redundant memory.

Explanation on why do I need this in the first place: sometimes I want to pass something to Collectors.groupingBy and then perform a stream operation on a downstream, without collecting it additional time.

Is there a simple way to do it (without writing my own class implementing the collector interface)?

EDIT: This question has been marked as a duplicate of this question, but that is not what I'm looking for. I do not want to duplicate the original stream, I want to close it and produce a new stream consisting of the same elements in the same order, by the means of Collector and without allocating memory in between.

Covariance
  • 67
  • 5
  • Collector, collects the stream into a collection. Before the collection it always is a stream. Why collect it if you still want to use the stream? Maybe I have not undestood something deeper that you meant, however it seems to me that you want to collect your stream and then stream it again. – Panagiotis Bougioukos Mar 28 '21 at 18:49
  • Construction I have described in the question is useful when I pass the Collector into another Collector, for example, `Collectors.groupingBy`, and thus, it will operate on another stream. – Covariance Mar 28 '21 at 18:54

1 Answers1

1

The collect method will accept a collector.

Parts of the collectors are the following

  • Supplier - For a stream, it could be Stream.empty() for example
  • Accumulator - For streams, we can use Stream.concat()
  • Combiner - Since this takes a BinaryOperator and you'll need to work on the first element because it will be the reference. For lists for example, you get l1 and l2 and usually do l1.addAll(l2)

So, further than being very complicated, the overhead in terms of memory allocation will be bigger than just collecting everything in a collection first.

Everything is possible, however, you'll probably need to write your own collector that will suite your needs.

You can even rewrite the same exact collector as groupingBy, but is it really worth it?

Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89