-1

I am trying to convert a character literal array into a character object array. Right now I am just using a for loop like:

char[] charLiterals = "abcdefghijklmnopqrstuvwxyz".toCharArray();
Character[] charObjects = new Character[charLiterals.length];

for (int character = 0; character < charLiterals.length; character++) {
    charObjects[character] = Character.valueOf(charLiterals[character]);
}

But is there a more concise way to do this?

sbottingota
  • 533
  • 1
  • 3
  • 18
  • 4
    Define better. Less code? More efficient? More readable? Also ... what version of Java are you targeting? – Stephen C Sep 25 '22 at 06:15

3 Answers3

1

A simple one liner would do.

Character[] charObjects = "abcdefghijklmnopqrstuvwxyz".chars().mapToObj(c -> (char)c).toArray(Character[]::new);
0

According to this article there are multiple ways to do that. But I believe that all of them under the hood boil down to an iteration similar to the one you provided.

If you don't mind using external libraries, then org.apache.commons.commons-lang3:3.12.0 might be the shortest and cleanest approach:

int[] input = new int[] { 0, 1, 2, 3, 4 };
Integer[] expected = new Integer[] { 0, 1, 2, 3, 4 };

Integer[] output = ArrayUtils.toObject(input);

assertArrayEquals(expected, output);
wheleph
  • 7,974
  • 7
  • 40
  • 57
0

Just leaving the part of converting String into Char array and directly assigning string's char value to Character array.

String str = "abcdefghijklmnopqrstuvwxyz";      
Character[] charObjects = new Character[str.length()];

for(int i = 0; i < str.length(); i++) {
    charObjects[i] = Character.valueOf(str.charAt(i));
}
sasi66
  • 437
  • 2
  • 7