Languages
[Edit]
EN

Java - convert char array to Character array

13 points
Created by:
Kate_C
2952

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
Hey 👋
Would you like to know what we do?
  • Dirask is online IT community for professionals and hobbyist to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.