Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert an String array to an Int array?

Tags:

java

arrays

I have made research for a couple hours trying to figure out how to convert a String array to a Int array but no luck.

I am making a program where you can encrypt a message by using three rotors. I am able to type a message and get the index number for the first rotor (inner rotor) to encrypt into the third rotor (outer rotor). The problem is the index number is in a string array which I want it to become a int array.

Yes, I have tried

int[] array == Arrays.asList(strings).stream()
        .mapToInt(Integer::parseInt).toArray();

or any form of that. I'm not unsure if I have java 8 since it doesn't work, but it gives me an error.

Can someone help me how to convert a String array to a Int array?

public void outerRotorEncrypt() {
    String[] indexNumberSpilt = indexNumber.split(" ");

    System.out.println("indexNumber length: " + indexNumber.length()); //test
    System.out.println("indexNumberSpilt length: " + indexNumberSpilt.length); //test
    System.out.println("Index Number Spilt: " + indexNumberSpilt[3]); //test
    System.out.println("");

    System.out.println("");
    System.out.println("testing from outerRotorEncrypt");
    System.out.println("");

    for(int i = 1; i < indexNumberSpilt.length; i++){
        secretMessage = secretMessage + defaultOuterRotorCharacterArray[indexNumberSpilt[i]];
    }
    System.out.println("Secret Message from outerRotorEncrypt: " + secretMessage);
}
like image 891
Allen Tran Avatar asked Dec 13 '25 00:12

Allen Tran


2 Answers

If you are using Java8 than this is simple way to solve this issue.

List<?> list = Arrays.asList(indexNumber.split(" "));
list = list.stream().mapToInt(n -> Integer.parseInt((String) n)).boxed().collect(Collectors.toList());

In first Line you are taking a generic List Object and convert your array into list and than using stream api same list will be filled with equivalent Integer value.

like image 125
Darshit Avatar answered Dec 14 '25 16:12

Darshit


static int[] parseIntArray(String[] arr) {
    return Stream.of(arr).mapToInt(Integer::parseInt).toArray();
}

So take a Stream of the String[]. Use mapToInt to call Integer.parseInt for each element and convert to an int. Then simply call toArray on the resultant IntStream to return the array.

like image 23
Lauyou.com Avatar answered Dec 14 '25 15:12

Lauyou.com



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!