BAEL-6714: Convert Char Array to Int Array in Java (#14875)

This commit is contained in:
Azhwani 2023-10-09 09:57:03 +02:00 committed by GitHub
parent 52f4344bce
commit 1f3252df75
2 changed files with 121 additions and 0 deletions

View File

@ -0,0 +1,67 @@
package com.baeldung.array.conversions;
import java.util.Arrays;
public class CharArrayToIntArrayUtils {
static int[] usingGetNumericValueMethod(char[] chars) {
if (chars == null) {
return null;
}
int[] ints = new int[chars.length];
for (int i = 0; i < chars.length; i++) {
ints[i] = Character.getNumericValue(chars[i]);
}
return ints;
}
static int[] usingDigitMethod(char[] chars) {
if (chars == null) {
return null;
}
int[] ints = new int[chars.length];
for (int i = 0; i < chars.length; i++) {
ints[i] = Character.digit(chars[i], 10);
}
return ints;
}
static int[] usingStreamApiMethod(char[] chars) {
if (chars == null) {
return null;
}
return new String(chars).chars()
.map(c -> c - 48)
.toArray();
}
static int[] usingParseIntMethod(char[] chars) {
if (chars == null) {
return null;
}
int[] ints = new int[chars.length];
for (int i = 0; i < chars.length; i++) {
ints[i] = Integer.parseInt(String.valueOf(chars[i]));
}
return ints;
}
static int[] usingArraysSetAllMethod(char[] chars) {
if (chars == null) {
return null;
}
int[] ints = new int[chars.length];
Arrays.setAll(ints, i -> Character.getNumericValue(chars[i]));
return ints;
}
}

View File

@ -0,0 +1,54 @@
package com.baeldung.array.conversions;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.jupiter.api.Test;
class CharArrayToIntArrayUtilsUnitTest {
@Test
void givenCharArray_whenUsingGetNumericValueMethod_shouldGetIntArray() {
int[] expected = { 2, 3, 4, 5 };
char[] chars = { '2', '3', '4', '5' };
int[] result = CharArrayToIntArrayUtils.usingGetNumericValueMethod(chars);
assertArrayEquals(expected, result);
}
@Test
void givenCharArray_whenUsingDigitMethod_shouldGetIntArray() {
int[] expected = { 1, 2, 3, 6 };
char[] chars = { '1', '2', '3', '6' };
int[] result = CharArrayToIntArrayUtils.usingDigitMethod(chars);
assertArrayEquals(expected, result);
}
@Test
void givenCharArray_whenUsingStreamApi_shouldGetIntArray() {
int[] expected = { 9, 8, 7, 6 };
char[] chars = { '9', '8', '7', '6' };
int[] result = CharArrayToIntArrayUtils.usingStreamApiMethod(chars);
assertArrayEquals(expected, result);
}
@Test
void givenCharArray_whenUsingParseIntMethod_shouldGetIntArray() {
int[] expected = { 9, 8, 7, 6 };
char[] chars = { '9', '8', '7', '6' };
int[] result = CharArrayToIntArrayUtils.usingParseIntMethod(chars);
assertArrayEquals(expected, result);
}
@Test
void givenCharArray_whenUsingArraysSetAllMethod_shouldGetIntArray() {
int[] expected = { 4, 9, 2, 3 };
char[] chars = { '4', '9', '2', '3' };
int[] result = CharArrayToIntArrayUtils.usingArraysSetAllMethod(chars);
assertArrayEquals(expected, result);
}
}