How to convert an ArrayList containing Integers to primitive int array?

前端 未结 18 1354
情书的邮戳
情书的邮戳 2020-11-22 11:23

I\'m trying to convert an ArrayList containing Integer objects to primitive int[] with the following piece of code, but it is throwing compile time error. Is it possible to

相关标签:
18条回答
  • 2020-11-22 11:49

    Java 8:

    int[] intArr = Arrays.stream(integerList).mapToInt(i->i).toArray();
    
    0 讨论(0)
  • 2020-11-22 11:52

    You can simply copy it to an array:

    int[] arr = new int[list.size()];
    for(int i = 0; i < list.size(); i++) {
        arr[i] = list.get(i);
    }
    

    Not too fancy; but, hey, it works...

    0 讨论(0)
  • 2020-11-22 11:53

    using Dollar should be quite simple:

    List<Integer> list = $(5).toList(); // the list 0, 1, 2, 3, 4  
    int[] array = $($(list).toArray()).toIntArray();
    

    I'm planning to improve the DSL in order to remove the intermediate toArray() call

    0 讨论(0)
  • 2020-11-22 11:54

    I believe iterating using the List's iterator is a better idea, as list.get(i) can have poor performance depending on the List implementation:

    private int[] buildIntArray(List<Integer> integers) {
        int[] ints = new int[integers.size()];
        int i = 0;
        for (Integer n : integers) {
            ints[i++] = n;
        }
        return ints;
    }
    
    0 讨论(0)
  • 2020-11-22 11:57

    This works nice for me :)

    Found at https://www.techiedelight.com/convert-list-integer-array-int/

    import java.util.Arrays;
    import java.util.List;
    
    class ListUtil
    {
        // Program to convert list of integer to array of int in Java
        public static void main(String args[])
        {
            List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
    
            int[] primitive = list.stream()
                                .mapToInt(Integer::intValue)
                                .toArray();
    
            System.out.println(Arrays.toString(primitive));
        }
    }
    
    0 讨论(0)
  • 2020-11-22 11:59

    You can convert, but I don't think there's anything built in to do it automatically:

    public static int[] convertIntegers(List<Integer> integers)
    {
        int[] ret = new int[integers.size()];
        for (int i=0; i < ret.length; i++)
        {
            ret[i] = integers.get(i).intValue();
        }
        return ret;
    }
    

    (Note that this will throw a NullPointerException if either integers or any element within it is null.)

    EDIT: As per comments, you may want to use the list iterator to avoid nasty costs with lists such as LinkedList:

    public static int[] convertIntegers(List<Integer> integers)
    {
        int[] ret = new int[integers.size()];
        Iterator<Integer> iterator = integers.iterator();
        for (int i = 0; i < ret.length; i++)
        {
            ret[i] = iterator.next().intValue();
        }
        return ret;
    }
    
    0 讨论(0)
提交回复
热议问题