Top community members

If you think it is valuable to share IT knowledge and help others.

It is the right place for you. ❤ 💻

Join our community.

[Edit]
EN

Java - convert char array to Character array

13 points
Created by:
Kate_C
2739

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

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more