Languages
[Edit]
EN

Java - convert character array to integer array

6 points
Created by:
Emorak
366

In this quick post, we are going to check how to convert character array to integer array in java.

1. Convert char[] to int[]

import java.util.Arrays;

public class Example1 {

    public static void main(String[] args) {
        char[] charArray = {'a', 'b', 'c'};
        int[] intArray = asIntArray(charArray);

        // [97, 98, 99]
        System.out.println(Arrays.toString(intArray));
    }

    public static int[] asIntArray(char[] charArray) {
        int[] result = new int[charArray.length];
        Arrays.setAll(result, i -> (int) charArray[i]);
        return result;
    }
}

Output:

[97, 98, 99]

2. Convert char[] to Integer[]

import java.util.Arrays;

public class Example2 {

    public static void main(String[] args) {
        char[] charArray = {'a', 'b', 'c'};
        Integer[] integerArray = asIntegerArray(charArray);

        // [97, 98, 99]
        System.out.println(Arrays.toString(integerArray));
    }

    public static Integer[] asIntegerArray(char[] charArray) {
        Integer[] result = new Integer[charArray.length];
        Arrays.setAll(result, i -> (int) charArray[i]);
        return result;
    }
}

Output:

[97, 98, 99]

3. Convert Character[] to int[]

import java.util.Arrays;

public class Example3 {

    public static void main(String[] args) {
        Character[] characterArray = {'a', 'b', 'c'};
        int[] intArray = asIntArray(characterArray);

        // [97, 98, 99]
        System.out.println(Arrays.toString(intArray));
    }

    public static int[] asIntArray(Character[] charArray) {
        return Arrays.stream(charArray).mapToInt(i -> (int) i).toArray();
    }
}

Output:

[97, 98, 99]

4. Convert Character[] to Integer[]

import java.util.Arrays;

public class Example4 {

    public static void main(String[] args) {
        Character[] characterArray = {'a', 'b', 'c'};
        Integer[] integerArray = asIntegerArray(characterArray);

        // [97, 98, 99]
        System.out.println(Arrays.toString(integerArray));
    }

    public static Integer[] asIntegerArray(Character[] charArray) {
        return Arrays.stream(charArray)
                .mapToInt(Integer::valueOf)
                .boxed()
                .toArray(Integer[]::new);
    }
}

Output:

[97, 98, 99]

 

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 conversion

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