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

前端 未结 18 1518
情书的邮戳
情书的邮戳 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:41

    Arrays.setAll()

        List x = new ArrayList<>(Arrays.asList(7, 9, 13));
        int[] n = new int[x.size()];
        Arrays.setAll(n, x::get);
    
        System.out.println("Array of primitive ints: " + Arrays.toString(n));
    

    Output:

    Array of primitive ints: [7, 9, 13]

    The same works for an array of long or double, but not for arrays of boolean, char, byte, short or float. If you’ve got a really huge list, there’s even a parallelSetAll method that you may use instead.

    To me this is good and elgant enough that I wouldn’t want to get an external library nor use streams for it.

    Documentation link: Arrays.setAll(int[], IntUnaryOperator)

提交回复
热议问题