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

前端 未结 18 1350
情书的邮戳
情书的邮戳 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: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 list = Arrays.asList(1, 2, 3, 4, 5);
    
            int[] primitive = list.stream()
                                .mapToInt(Integer::intValue)
                                .toArray();
    
            System.out.println(Arrays.toString(primitive));
        }
    }
    

提交回复
热议问题