EN
Java - convert char array to Character array
13 points
In this post we cover how to convert char[] to Character[] in 3 different ways.
Simplest way to do it:
xxxxxxxxxx
1
char[] charArr = {'a', 'b', 'c'};
2
3
Character[] charArrBoxed = new String(charArr).chars()
4
.mapToObj(c -> (char) c)
5
.toArray(Character[]::new);
xxxxxxxxxx
1
import java.util.Arrays;
2
3
public class Example1 {
4
5
public static void main(String[] args) {
6
7
char[] charArr = {'a', 'b', 'c'};
8
9
Character[] charArrBoxed = new String(charArr).chars()
10
.mapToObj(c -> (char) c)
11
.toArray(Character[]::new);
12
13
System.out.println(Arrays.toString(charArrBoxed)); // [a, b, c]
14
}
15
}
Output:
xxxxxxxxxx
1
[a, b, c]
xxxxxxxxxx
1
import java.util.Arrays;
2
import java.util.stream.IntStream;
3
4
public class Example2 {
5
6
public static void main(String[] args) {
7
8
char[] charArr = {'a', 'b', 'c'};
9
10
Character[] charArrBoxed = IntStream.range(0, charArr.length)
11
.mapToObj(idx -> charArr[idx])
12
.toArray(Character[]::new);
13
14
System.out.println(Arrays.toString(charArrBoxed)); // [a, b, c]
15
}
16
}
Output:
xxxxxxxxxx
1
[a, b, c]
xxxxxxxxxx
1
import java.nio.CharBuffer;
2
import java.util.Arrays;
3
4
public class Example3 {
5
6
public static void main(String[] args) {
7
8
char[] charArr = {'a', 'b', 'c'};
9
10
Character[] charArrBoxed = CharBuffer.wrap(charArr)
11
.chars().mapToObj(i -> (char) i)
12
.toArray(Character[]::new);
13
14
System.out.println(Arrays.toString(charArrBoxed)); // [a, b, c]
15
}
16
}
Output:
xxxxxxxxxx
1
[a, b, c]