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?
You obtain a stream from a collection by calling the stream() method of the given collection. Here is an example of obtaining a stream from a collection: List<String> items = new ArrayList<String>(); items.
The toMap collector can be used to collect Stream elements into a Map instance. To do this, we need to provide two functions: keyMapper.
Stream filter() is an intermediate operation and returns a stream. So, we will use the collect() function to create the list from this stream. The Collectors. toList() returns a Collector implementation that accumulates the input elements into a new List.
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?
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