ilomambo
ilomambo

Reputation: 8350

Getting a List<Integer> from a resource array

I have a string-array resource with integers.

<string-array name="navChildRatings">
    <item>12</item>
    <item>12</item>
    <item>17</item>
    <item>123</item>
    <item>8</item>

</string-array>

My goal is to have them into a list of type List<Integer>
As a first step I know they can be assigned into an integer array by:

int[] ratings = Arrays.asList(getResources().getIntArray(R.array.navChildRatings));

I am trying to avoid looping through the array of integers (ints) and having to add one by one to the List of Integers (java.lang.Integer).

  1. Is there a direct way to get the string-array into a List<Integer>?
    or, alternatively
  2. Is there a direct way to assign the int[] array to a List<Integer>?

Note: My motivation is purely to have a more elegant code. I know how to do it by looping the array. But, for example, in the case of Strings it works if you assign it directly:

List<String> names = Arrays.asList(getResources().getStringArray(R.array.navChildNames));

Upvotes: 0

Views: 352

Answers (1)

m.antkowicz
m.antkowicz

Reputation: 13571

Unofortunately this is impossible since asList is not handling boxing (wrapping primitive) and will not create objects automatically.

If you want to keep code elegant and using Java8 you can easily create lambda to do it as one-liner

if you do not use Java8 just create a simple method to convert int[] to List

    ArrayList<Integer> getList(int[] a)
    {
        List<Integer> l = new ArrayList<Integer>();

        for(int i : a)
            l.add( new Integer(i) );

        return l;
    }

and then

    List<Integer> items = getList(ratings);

Upvotes: 1

Related Questions