I have quite a lot spots in my code which do:
someStream.collect(Collectors.toList())
where Collectors.toList()
creates a new collector on every use.
This leads me to the question if it is allowed and advisable to do something like:
private final static Collector<…> TO_LIST = Collectors.toList()
for every type I use and then make use of that single Collector like:
someStream.collect(TO_LIST)
when a collector is required.
As the collectors are stateless and just a collection of functions and characteristics, I should think it should work, but OTOH, Collectors.toList()
creates a new CollectorImpl<>
on every call.
What are the downsides of reusing a Collector?
I think this is more of a style question, but lets give some thoughts:
What I mean with that: if you are worried of "wasting" performance; you would rather look into each and any line of code that uses streams to determine whether that stream is working with "enough" objects to justify the usage of streams in the first place. Those streams come with quite some overhead!
Long story short: the java community has yet to find "standard best practices" for streams; thus my (personal) two cent at this time: prefer those patterns that "everybody" is using - avoid doing your own thing. Especially when it is "performance related".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With