A collector that returns an array

I have the following code:

strings.stream().map( i->i.toUpperCase()).collect(Collectors.toList());

      

The above code returns List

I want to get an analog that will return an array.

Is this possible without additional method call toArray

?

+3


source to share


2 answers


The class Stream

has two methods toArray

- here's an example with Stream :: toArray (IntFunction) ` :



String[] array = strings.stream().toArray(String[]::new);

      

+6


source


If you really need a collector (for example, to be used as a downstream for groupingBy

), you can create one in a fairly simple way:



Collector<String, ?, String[]> toArrayCollector = 
        Collectors.collectingAndThen(Collectors.toList(),
                list -> list.toArray(new String[list.size()]));

      

+3


source







All Articles