Question

I have a String array that contains {127,a,0,10}. I want to grab the numbers in that array and place them into an int array that will now contain {127,0,10}.

I tried to use parseInt on each individual value in the String array but it does not worked on characters in a string.

Thank you!

Was it helpful?

Solution

The Java 8 answer:

int[] results = Arrays.stream(arr)
                    .filter(s -> s.matches("-?[0-9]+"))
                    .mapToInt(s -> Integer.parseInt(s))
                    .toArray();

EDIT: Even better:

int[] results = Arrays.stream(arr)
                    .filter(s -> s.matches("-?[0-9]+"))
                    .mapToInt(Integer::parseInt)
                    .toArray();

demonstrating yet another new cool language feature. I should have seen this the first time. It's pathetic that I haven't yet mastered Java 8 despite its being officially available for a whole two weeks now.

OTHER TIPS

Validate int value

You could create a function that would tell you if a string represents valid int value as so:

public static boolean isInteger(String s) {
    try { 
        Integer.parseInt(s); 
    } catch(NumberFormatException e) { 
        return false; 
    }
    // only got here if we didn't return false
    return true;
}

Source: Determine if a String is an Integer in Java

Remove unwanted elements

You can now easily loop on the array and remove unwanted elements as so:

for(int i=0; i< myStringArray.length(); i++){
    if(!isInteger(myStringArray[i])){
        myStringArray[i]=null;
    }
}

I tried to use parseInt on each individual value in the String array but it does not worked on characters in a string.

parseInt does not work for characters, that is by design of that API. It will throw an exception in case of invalid numeric value. So what you have to do is encapsulate your code in try/catch. And in case of NumberFormatException don't put the item in second array, otherwise add. Hope you will be able to code this.

Try something like this

Integer[] numberArray = new Integer[stringArray.length];
int index = 0;
for(String s : stringArray) {
    try {
        Integer stringAsNumber = Interger.valueOf(s);
        numberArray[index] = stringAsNumber;
        index++;
    } catch(NumberFormatException nfe) {
        //String is not a valid number
    }
 }
 return numberArray;

You can use a regex to determine if a string can be parsed into an Integer.

String [] arr = {"1233", "45", "a34", "/", "0", "19"};
for(int i = 0; i < arr.length; i++)
    if(arr[i].matches("-?[0-9]+"))
        System.out.println(arr[i]);

The rest is easy to do.

EDIT: This detects both positive and negative numbers.

try this..

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.ArrayList;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String[] var = new String[]{"127","a","0","10"};
        List<Integer> var2 = new ArrayList<Integer>();
            //Integer extraction
        for (String s : var) 
        {
            try{
                var2.add(Integer.parseInt(s));
                    System.out.println(Integer.parseInt(s));

                }catch(NumberFormatException e){}
        }
            //int array if you want array only or you just use List<Integer>
            int[] array = new int[var2.size()];
            for(int i = 0; i < var2.size(); i++) array[i] = var2.get(i);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top