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();
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]
Works like a charm! +1 becuase you arren't a "This wont work"- person :P
IntStream.range('a', 'z' + 1)
can be replaced withIntStream.rangeClosed('a', 'z')
@Pshemo, thx, it may belong as a comment to the question (from where I took
IntStream.range('a', 'z' + 1)
), but in any case, it’s clearly more readable.A downside to this solution is that a String object is created for each array element — this could be a performance / memory consideration for larger arrays.