EN
Java - convert character array to integer array
6 points
In this quick post, we are going to check how to convert character array to integer array in java.
xxxxxxxxxx
1
import java.util.Arrays;
2
3
public class Example1 {
4
5
public static void main(String[] args) {
6
char[] charArray = {'a', 'b', 'c'};
7
int[] intArray = asIntArray(charArray);
8
9
// [97, 98, 99]
10
System.out.println(Arrays.toString(intArray));
11
}
12
13
public static int[] asIntArray(char[] charArray) {
14
int[] result = new int[charArray.length];
15
Arrays.setAll(result, i -> (int) charArray[i]);
16
return result;
17
}
18
}
Output:
xxxxxxxxxx
1
[97, 98, 99]
xxxxxxxxxx
1
import java.util.Arrays;
2
3
public class Example2 {
4
5
public static void main(String[] args) {
6
char[] charArray = {'a', 'b', 'c'};
7
Integer[] integerArray = asIntegerArray(charArray);
8
9
// [97, 98, 99]
10
System.out.println(Arrays.toString(integerArray));
11
}
12
13
public static Integer[] asIntegerArray(char[] charArray) {
14
Integer[] result = new Integer[charArray.length];
15
Arrays.setAll(result, i -> (int) charArray[i]);
16
return result;
17
}
18
}
Output:
xxxxxxxxxx
1
[97, 98, 99]
xxxxxxxxxx
1
import java.util.Arrays;
2
3
public class Example3 {
4
5
public static void main(String[] args) {
6
Character[] characterArray = {'a', 'b', 'c'};
7
int[] intArray = asIntArray(characterArray);
8
9
// [97, 98, 99]
10
System.out.println(Arrays.toString(intArray));
11
}
12
13
public static int[] asIntArray(Character[] charArray) {
14
return Arrays.stream(charArray).mapToInt(i -> (int) i).toArray();
15
}
16
}
Output:
xxxxxxxxxx
1
[97, 98, 99]
xxxxxxxxxx
1
import java.util.Arrays;
2
3
public class Example4 {
4
5
public static void main(String[] args) {
6
Character[] characterArray = {'a', 'b', 'c'};
7
Integer[] integerArray = asIntegerArray(characterArray);
8
9
// [97, 98, 99]
10
System.out.println(Arrays.toString(integerArray));
11
}
12
13
public static Integer[] asIntegerArray(Character[] charArray) {
14
return Arrays.stream(charArray)
15
.mapToInt(Integer::valueOf)
16
.boxed()
17
.toArray(Integer[]::new);
18
}
19
}
Output:
xxxxxxxxxx
1
[97, 98, 99]