How can we convert List<Character> into an Array char[] with Java 8

Viewed 48

A solution I came up with is to create a String from the stream elements.

Like this:

listChars.stream()
    .map(String::valueOf)
    .collect(Collectors.joining()
    .toCharArray();

How it can be done without converting into a String?

1 Answers

There's no separate flavor of primitive streams for char type, for that reason this conversion with stream can't be done in such a straightforward way like, for instance, conversion List<Integer> to int[] with IntStream.

To turn a List of Character into an array char[] using streams, you can use CharBuffer as accumulation type.

That would allow avoiding making unnecessary copies of the data (which would take place with String and StringBuilder) because CharBuffer gives you access to its underlying array via CharBuffer.array() (in case when it's baked by an array).

That's how we can create a collector based on a CharBuffer:

char[] result = listChars.stream()
    .collect(Collector.of(
        () -> CharBuffer.allocate(listChars.size()), // allocating the underlying array
        CharBuffer::append,                          // accumulating stream elements
        CharBuffer::append,                          // merging buffers in parallel
        CharBuffer::array                            // finisher function - extracting the backing array as a final action
    );
Related