Languages
[Edit]
EN

Java - convert character array to integer array

6 points
Created by:
Kate_C
2860

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]

 

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists 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.