Warm tip: This article is reproduced from stackoverflow.com, please click
arrays java converter primitive-types

Converting int array to char array

发布于 2020-03-30 21:12:35

Is it possible to cast an int array to a char array? If so - how?


I'm currently working on a project where I need to create an char array containing the alphabet. My current code creats an int array (which should be converted to an char array - in one Line!):

return IntStream.range('a', 'z' + 1).toArray();

Questioner
TheRealVira
Viewed
19
Ole V.V. 2017-08-12 04:32

Yeah, we’re missing a stream method to produce a char array. Maybe a whole CharStream class. In any case, no, you cannot cast between int[] and char[].

In the meantime, it’s getting a long line, but it works:

    return IntStream.rangeClosed('a', 'z')
            .mapToObj(c -> Character.toString((char) c))
            .collect(Collectors.joining())
            .toCharArray();

This gives a char[] containing

[a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z]