What's a simple way to convert/flatten a List<char[]> to char[] in Java?
I know I can do it by iterating the List and using System.arraycopy, but I'm wondering is there a simpler way to do it using Java 8 streams?
Maybe something like this, but without having to box the primitive char to Character:
List<char[]> listOfCharArrays = ...
Character[] charArray =
Stream.of(listOfCharArrays )
.flatMap(List::stream)
.toArray(Character[]::new);
This is the most readable version I can come up with. You can append all the char arrays to a String, via a StringBuilder, then convert that to a char[].
char[] chars = listOfCharArrays.stream()
.collect(Collector.of(StringBuilder::new, StringBuilder::append, StringBuilder::append, StringBuilder::toString))
.toCharArray();
Probably much slower than the iterative version, since arrayCopy can copy blocks of memory.
You could consider precomputing the total number of chars to avoid StringBuilder array reallocations, but this optimization and any others are going to eat into the readability gains you're getting from using streams.
int totalSize = listOfCharArrays.stream().mapToInt(arr -> arr.length).sum();
char[] chars = listOfCharArrays.stream()
.collect(Collector.of(() -> new StringBuilder(totalSize), //... the same
There are 2 unnecessary copies (StringBuilder -> String, String -> char[]) which are effectively a consequence of these classes not being perfectly suited to this task. CharBuffer is better suited; see Maarten's answer.
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