I've tried to find a good way to set up initial capacity of collector in java stream api. The simplest example is there:
data.stream()
.collect(Collectors.toList());
I just want to pass an int with size of list into collector in order not to resize internal array. The first intention is to do it in such way:
data.stream()
.collect(Collectors.toList(data.size()));
But unfortunately toList isn't overloaded to work with parameter. I found one solution but it smells:
data.stream()
.collect(Collectors.toCollection(() -> new ArrayList<>(data.size())));
Is there any way to express it simplier?
toList()doesn't specify the list it returns. Why do you assume it is ArrayList, or that the list returned understand a concept of "initial capacity"? (Yes, it currently is anArrayList, but this is an implementation detail, and not all lists have an initial capacity).ArrayList::newsince you need to pass the initial capacity... Make your own method returning theSupplier<List<T>>if you find the number of closing parenthesis too much.