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.

2

6 Answers 6

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;
}
4
  • It throws an exception. NumberFormatException. Even if it is catched? Why? Feb 27, 2018 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 Feb 27, 2018 at 15:28
  • I am still getting just a 2. Feb 27, 2018 at 15:41
  • @ismael oliva use String[] strings = stringToList.split(",\\s+"); if you have multiple whitespaces.
    – xingbin
    Feb 27, 2018 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

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”

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.

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
2
  • At the end the list returns just 2 Feb 27, 2018 at 15:39
  • @ismaeloliva nope : ideone.com/XZkBqE , print you String before to be sure what to give to the function
    – azro
    Feb 27, 2018 at 15:41
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));

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.