How to filter integers and copy them to a new array from a String

2.8k Views Asked by At

Having a string (any string). It may not contain numbers;

How can I store the integers contained in that array into an ArrayList.

Tried to

public ArrayList<Integer> toList() {
    String stringToList;
    ArrayList<Integer> l = new ArrayList<>();
    stringToList = this.toString(); // I am just copying the string from the object
    for (int i = 0; i < stringToList.length(); i++) {
        if(((Integer) stringToList.charAt(i)) instanceof Integer){
                 //Here store it into the arrayList
                }             
    }
    return l;
}

But obviously it does not work because the cast is not the solution. Any ideas? Thanks.

6

There are 6 best solutions below

4
xingbin On

Since there may exist such as 12 in the string, you can not use charAt() directly. You can split the stringToList with , and then use Integer.parseInt()

public ArrayList<Integer> toList() {
    String stringToList;
    ArrayList<Integer> l = new ArrayList<>();
    stringToList = this.toString(); // I am just copying the string from the object
    String[] strings = stringToList.split(",\\s+");
    for (int i = 0; i < strings.length; i++) {
        try {
            l.add(Integer.parseInt(strings[i]));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }
    return l;
}
0
Starx On

You can split the string, like

String[] splits = stringToList.split(",");

And cast them to integer using something like Integer.parseInt(splits[0]); and store them in an ArrayList

0
Tim Lee On

You can check if the character is a number by using the Character.isDigit method.

if (Character.isDigit(stringToList.charAt(0))){
    l.add((int)stringToList.charAt(0));
}

And cast the char to an int before you add into the arraylist of integers.

2
azro On

Parse, Check, Convert, Collect in one-line way :

This solution can parse any String because it'll check, before converting to Integer that each part taken from split is only composed of digits (or with a minus before)

String str = "1 , 2, 2a, 3,    -14, b55";
List<Integer> list =  Arrays.stream(str.split(","))
                            .map(String::trim)
                            .filter(s -> s.matches(""-?\\d+""))
                            .map(Integer::valueOf)
                            .collect(Collectors.toList());
System.out.println(list);     // list : [1, 2, 3, -14]
  • split the String on comma
  • make a Stream of it
  • remove the spaces around
  • check that there is only digits
  • convert each element to an Integer
  • collect them into a List
0
Adrian V On

If you are using Java 8 you can try the following:

public ArrayList<Integer> toList(String input) {
    return Arrays.stream(input.split(","))
                 .map(String::trim)
                 .filter(s -> s.matches("\\b\\d+\\b"))
                 .map(Integer::valueOf)
                 .collect(Collectors.toCollection(ArrayList::new));

}
0
Abhi On

Code Example : (Execution)

enter image description here

import java.util.Arrays;
import java.util.Scanner;

public class Scann {
    Scanner s;

    Scann() {
        s = new java.util.Scanner(System.in);
        System.out.println("Enter string : \n");

        String str = s.nextLine();
        str = str.replaceAll("[^-?0-9]+", " ");
        System.out.println(Arrays.asList(str.trim().split(" ")));
    }

    public static void main(String args[]) {

        new Scann();
    }

}

Description : [^-?0-9]+

+ Between one and unlimited times, as many times as possible, giving back as needed

-? One of the characters “-?”

0-9 A character in the range between “0” and “9”