Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 924
the_kaba Avatar asked Dec 09 '16 21:12

the_kaba


People also ask

Which is the correct way of obtaining a Stream from the collection?

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.

Which method of collector class can be used to store the result of a Stream in map?

The toMap collector can be used to collect Stream elements into a Map instance. To do this, we need to provide two functions: keyMapper.

Which method of streams API is used to collect Stream elements into a List set?

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.


1 Answers

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?

like image 68
Mz A Avatar answered Sep 30 '22 17:09

Mz A