Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Arraylist<String> to an ArrayList<Integer> or Integer Array [closed]

I wanna make an apps that need to convert ArrayList<String>[] to ArrayList<Integer>[] , I also used this :

ArrayList<String>[] strArrayList;
int ArrayRes = (int) strArrayList[];

but this code get me an error , anybody can help me ?

Any suggestion would be appreciate

like image 256
Mr.James Avatar asked Oct 10 '11 04:10

Mr.James


People also ask

Can we convert String to ArrayList in Java?

Converting String to ArrayList means each character of the string is added as a separator character element in the ArrayList. We can easily convert String to ArrayList in Java using the split() method and regular expression.


2 Answers

Define a method which will convert all String value of arraylist into 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 simply call that method, as

ArrayList<Integer> resultList = getIntegerArray(strArrayList); //strArrayList is a collection of Strings as you defined.

Happy coding :)

like image 163
Pankaj Kumar Avatar answered Nov 03 '22 00:11

Pankaj Kumar


How about this one

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

    }
like image 43
Dead Programmer Avatar answered Nov 02 '22 23:11

Dead Programmer