0

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));
9
  • 2
    Shouldn't that be an <integer-array>? Commented Jan 24, 2016 at 18:51
  • Maybe you are right, I will test it and let you know. Commented Jan 24, 2016 at 18:59
  • It still won't get your code to work the way you want but at least you won't have to parse the strings into Integers. You will have to use a for loop if you need a List<Integer> from the int[]. To keep it elegant you can write your own helper method that takes an int[] and returns a List<Integer> so you only have to write the loop once. Commented Jan 24, 2016 at 19:01
  • Duplicate of: stackoverflow.com/questions/1073919/… Commented Jan 24, 2016 at 19:02
  • @MarcoAltieri Not a duplicate. I am trying to avoid looping, which is not addressed in that question. Commented Jan 24, 2016 at 19:04

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Is this something I can do for Android java? I am not sure it is Java8
It isn't, Android uses Java 7
if you are using this very often just create a simple method to convert int[] array

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.