Converting int array to char array

13,560

Solution 1

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]

Solution 2

From Java-11 and onwards , you can use .mapToObj(Character::toString) instead of .mapToObj(c -> Character.toString((char) c)) , so your overall code boils down to :

return IntStream.rangeClosed('a', 'z')
        .mapToObj(Character::toString)
        .collect(Collectors.joining())
        .toCharArray();

Solution 3

Let's keep it one line then:

return IntStream.range('a', 'z' + 1).mapToObj(i -> Character.valueOf((char) i)).toArray(Character[]::new);

This converts from IntStream, to Stream<Character>. Keep in mind chars and ints are essentially the same in terms of many calculations, so this step may be unnecessary (especially for comparisons).

Edit:

Fixed the above line to be functional, there is a better solution but I'm still trying to find it again. It currently returns a Character[] array.

Without the 1 line restriction it's simple to just remake the array, treating a as your 0 index.

char[] back = new char[('z' + 1) - 'a'];
IntStream.range('a', 'z' + 1).forEach(i -> back[i - 'a'] = (char) i);
return back;
Share:
13,560
TheRealVira
Author by

TheRealVira

Pulse rises ➡️ Finger tremble ➡️ A sudden scream... ➡️ "Program built successfully." | Vira, crafting next level software solutions.

Updated on June 28, 2022

Comments

  • TheRealVira
    TheRealVira almost 2 years

    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();

    • Vishal Goyal
      Vishal Goyal over 7 years
      If you want to convert a digit (0-9), you can add 48 to it and cast, or something like Character.forDigit(a, 10);.
    • Mohsen_Fatemi
      Mohsen_Fatemi over 7 years
      yes it is possible , just convert your number into 16 based number , consists of a-f and 0-9 :))
    • Andreas
      Andreas over 7 years
      No, you can't cast int[] to char[]. Also, your current code doesn't work, so it doesn't matter how short it is. First rule of optimization: It has to work. Since Java 8 doesn't have a CharStream, you should do it with a normal for loop. It only takes 3 lines of code (4 with return statement), and it works!
  • TheRealVira
    TheRealVira over 7 years
    that's what I'm talking about! The only problem is, that it returns an object array - how can I cast it to an char array? :3
  • hasan
    hasan over 7 years
    i am not sure if its just my compiler but your solution leads to following error for me: Error: java: incompatible types: java.lang.Integer cannot be converted to char
  • Rogue
    Rogue over 7 years
    No you're both correct, there's a better way I'll edit it in in just a moment.
  • TheRealVira
    TheRealVira over 7 years
    Works like a charm! +1 becuase you arren't a "This wont work"- person :P
  • Alex Klimashevsky
    Alex Klimashevsky over 7 years
    @TheRealVira streams does it. not arrays
  • Ole V.V.
    Ole V.V. over 7 years
    Just to keep the usage correct, @AlexKlimashevsky is correct, my answer is not doing a cast, but solving your problem by other means.
  • TheRealVira
    TheRealVira over 7 years
    @AlexKlimashevsky plus there is a way to get a stream from your array: stackoverflow.com/questions/27888429/…
  • Pshemo
    Pshemo over 6 years
    IntStream.range('a', 'z' + 1) can be replaced with IntStream.rangeClosed('a', 'z')
  • Ole V.V.
    Ole V.V. over 6 years
    @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.
  • Mat Gessel
    Mat Gessel over 4 years
    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.