An elegant way to specify initial capacity of Collector in java stream api

亡梦爱人 提交于 2019-12-04 06:31:55

I'd take your inelegant

Collectors.toCollection(() -> new ArrayList<>(data.size()))

and wrap it in a static method

public static <T> Collector<T, ?, List<T>> toList(int size) {
    return Collectors.toCollection(() -> new ArrayList<T>(size));
}

then call it (with a static import)

stream.collect(toList(size))

!inelegant?

edit (This does make it an ArrayList) is this bad?

I do not know of any straightforward way in the API to ensure the capacity of the mutable container used under the hood to collect the data. I may guess that at least one of the many reasons is the support for parallelism by calling parallelStream().

So - if your data is processed in parallel there is no much sense to give initial capacity even if you know that the underlying container (e.g. ArrayList) supports capacity. Multiple containers will be created by different threads and later combined and the capacity will at least harm the overall performance.

If you want to be truly specific and elegant you may also try to implement your own collector. It is not difficult.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!