0

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!

user3369494
  • 123
  • 11

6 Answers6

4

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.

ajb
  • 31,309
  • 3
  • 58
  • 84
  • Java 8 might be missing some mapping methods that are able to exclude elements from the output if they are unable to return a result. Maybe we need a version of `parseInt` that returns an `OptionalInteger`, and a stream mapping method like `mapToInt` that works on functions that return `OptionalInt` and discards the results where `isPresent` is false? Then I could remove a whole item from the pipeline. – ajb Apr 02 '14 at 00:27
2

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;
    }
}
Community
  • 1
  • 1
0x9BD0
  • 1,542
  • 18
  • 41
0

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.

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
0

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.

turingcomplete
  • 2,128
  • 3
  • 16
  • 25
  • 1
    Be carefull with "asa123asda" strings, it could break your code. Better use ^ and $ delimiters – SerCrAsH Apr 01 '14 at 23:57
  • Good idea, always good to be safe :). Although I couldn't find an example that would break it. Nevertheless, thanks for the suggestion, I updated my answer. – turingcomplete Apr 02 '14 at 00:14
  • 2
    `matches` always requires the entire string to match. – ajb Apr 02 '14 at 00:17
0

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;
jcmwright80
  • 2,599
  • 1
  • 13
  • 15
0

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);
    }
}
Dexters
  • 2,419
  • 6
  • 37
  • 57