To convert a char[] to a Character[] array, we're first going to build a representative test ASCII char array from an IntStream, by using an accordingly size-allocated CharBuffer, inside a custom Collector (built from Supplier, Accumulator, Combiner and finisher Function):
Collector<Character, CharBuffer, char[]> charArrayCollector = Collector.of(
() -> CharBuffer.allocate(95),
CharBuffer::put,
CharBuffer::put,
CharBuffer::array
);
Then, we can create an array from the standard printable ASCII range. Using .range() instead of .iterate() saves the need of limiting the resulting stream afterwards.
The iterated int values are cast to char each and mapped to a 'boxed' Character object stream, which is then collected into the test char[] array:
char[] asciiChars = IntStream.range(32, 127)
.mapToObj(i -> (char)i)
.collect(charArrayCollector);
Now, we can convert the ASCII char[] array, again using an IntStream. This surrogates a classic for loop, by iterating over the array's indices, mapping each contained char into stream of 'boxed' Character objects, finally creating the desired Character[] array in the terminal operation. Stream.iterate is just for demonstration of an alternative way:
Character[] characters = IntStream.range(0, asciiChars.length)
.mapToObj(i -> Character.valueOf(chars[i]))
.toArray(Character[]::new);
Character[] characters2 = Stream.iterate(0, i -> i += 1)
.map(i -> asciiChars[i])
.limit(asciiChars.length)
.toArray(Character[]::new);
Edit:
Other primitive type arrays can be converted similarly; here, the boxing occurs in the .mapToObj() intermediate operation, where the source array elements are extracted and mapped to their object counterparts:
byte[] bytes = new byte[] { Byte.MIN_VALUE, -1 , 0, 1, Byte.MAX_VALUE };
Byte[] boxedBytes = IntStream.range(0, bytes.length)
.mapToObj(i -> bytes[i])
.toArray(Byte[]::new);
short[] shorts = new short[] { Short.MIN_VALUE, -1, 0, 1, Short.MAX_VALUE };
Short[] boxedShorts = IntStream.range(0, shorts.length)
.mapToObj(i -> shorts[i])
.toArray(Short[]::new);
float[] floats = new float[] { Float.MIN_VALUE, -1.0f, 0f, 1.0f, Float.MAX_VALUE };
Float[] boxedFLoats = IntStream.range(0, floats.length)
.mapToObj(i -> floats[i])
.toArray(Float[]::new);
For primitive values supported by the Stream API, the corresponding dedicated stream implementations and .boxed()can be used instead:
int[] ints = new int[] { Integer.MIN_VALUE, -1, 0, 1, Integer.MAX_VALUE };
Integer[] integers = IntStream.of(ints)
.boxed()
.toArray(Integer[]::new);
long[] longs = new long[] { Long.MIN_VALUE, -1l, 0l, 1l, Long.MAX_VALUE };
Long[] boxedLongs = LongStream.of(longs)
.boxed()
.toArray(Long[]::new);
double[] doubles = new double[] { Double.MIN_VALUE, -1.0, 0, 1.0, Double.MAX_VALUE };
Double[] boxedDoubles = DoubleStream.of(doubles)
.boxed()
.toArray(Double[]::new);