Languages
[Edit]
EN

Java - convert character array to integer array

6 points
Created by:
Kate_C
19800

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]

 

Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join