Convert Arraylist <String> to ArrayList <Integer> or Integer Array
5 answers
Define a method that converts the entire string value of an arraylist to an integer.
private ArrayList<Integer> getIntegerArray(ArrayList<String> stringArray) {
ArrayList<Integer> result = new ArrayList<Integer>();
for(String stringValue : stringArray) {
try {
//Convert String to Integer, and store it into integer array list.
result.add(Integer.parseInt(stringValue));
} catch(NumberFormatException nfe) {
//System.out.println("Could not parse " + nfe);
Log.w("NumberFormat", "Parsing failed! " + stringValue + " can not be an integer");
}
}
return result;
}
And just call this method how
ArrayList<Integer> resultList = getIntegerArray(strArrayList); //strArrayList is a collection of Strings as you defined.
Happy coding :)
+11
How about this
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class sample7
{
public static void main(String[] args)
{
ArrayList<String> strArrayList = new ArrayList<String>();
strArrayList.add("1");
strArrayList.add("11");
strArrayList.add("111");
strArrayList.add("12343");
strArrayList.add("18475");
List<Integer> newList = new ArrayList<Integer>(strArrayList.size()) ;
for (String myInt : strArrayList)
{
newList.add(Integer.valueOf(myInt));
}
System.out.println(newList);
}
}
+5