0

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.

ismael oliva
  • 97
  • 1
  • 3
  • 11
  • You have to "convert" the current char first to an Integer object and than chek it to null. Your code can run into a class cast exception while the VM tries to cast a colon into an incompatible datatype. – Reporter Feb 27 '18 at 15:15
  • Possible duplicate of [How to extract numbers from a string and get an array of ints?](https://stackoverflow.com/questions/2367381/how-to-extract-numbers-from-a-string-and-get-an-array-of-ints) – GalAbra Feb 27 '18 at 15:19

6 Answers6

2

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;
}
xingbin
  • 27,410
  • 9
  • 53
  • 103
  • It throws an exception. NumberFormatException. Even if it is catched? Why? – ismael oliva Feb 27 '18 at 15:23
  • Basically, the string can be any String. So no just "1, 2, 3" but any, like "a, sodcomsd, iowqowi, 2233, kdiqwdq, 123123". Notice they are separated by commas. I want to get those integers inside that string and store them into the arrayList – ismael oliva Feb 27 '18 at 15:28
  • I am still getting just a 2. – ismael oliva Feb 27 '18 at 15:41
  • @ismael oliva use `String[] strings = stringToList.split(",\\s+");` if you have multiple whitespaces. – xingbin Feb 27 '18 at 15:50
1

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

Starx
  • 77,474
  • 47
  • 185
  • 261
1

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”

Abhi
  • 995
  • 1
  • 8
  • 12
0

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.

Tim Lee
  • 358
  • 2
  • 8
0

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
azro
  • 53,056
  • 7
  • 34
  • 70
0

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));

}
Adrian V
  • 1
  • 2