Languages
[Edit]
EN

Java - convert char array to Character array

13 points
Created by:
Abel-Burks
758

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]

Merged questions

  1. Java - convert primitive char array to Character object array
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java - Arrays (popular problems)

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join