Pratik Jaiswal Pratik Jaiswal - 6 months ago 10
Java Question

Filter Java list and create integer constants array

I have a

Java list of Strings
as below:

myList:

C26366
C10025, C10026
C10244
C26595
C26594
C9026, C9027, C9029, C9080 //this is one list element (needs seperation)
C26597
C10223, C10287, C10277, C10215
C10242
C10243
C9025, C9030, C9034, C9051, C9052, C9055 // similarly here
C10241
C10067
C27557
C10066
.... //these are all ids


Above is an output of below
for-loop
snippet:

for (String id: myList) {
System.out.println(id);
}


How do I convert this myList into a Java integer array? I am expecting something like/I want to use use that array as:

public static final IDS = { 31598,9089,9092,9093,9108,9109,....}


IDS array
must hold the content from
myList
and they are without any
C's
in them and no other characters, but just the numbers.

Answer

I would suggest to do this:

  1. Define a list of integers for the final values
  2. then use Regex with this pattern "\d+" to find in the list of strings only the things that are numeric
  3. if found, parse it to integer and add it to the list.

Example:

List<Integer> myListIntegers = new ArrayList<Integer>();
for (String subStrings : myList) {
    Pattern p = Pattern.compile("\\d+");
    Matcher m = p.matcher(subStrings);
    while (m.find()) {
        myListIntegers.add(Integer.parseInt(m.group()));
    }
}
System.out.println(myListIntegers);

this code will print the list holding the insteger you have in myList

[26366, 10025, 10026, 10244, 26595, 26594, 9026, 9027, 9029, 9080, 10241, 10067, 27557, 10066]