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