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

前端 未结 18 1509
情书的邮戳
情书的邮戳 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() will work for most scenarios:

    1. Integer List to primitive int array:

      public static int[] convert(final List list)
      {
         final int[] out = new int[list.size()];
         Arrays.setAll(out, list::get);
         return out;
      }
      
    2. Integer List (made of Strings) to primitive int array:

      public static int[] convert(final List list)
      {
         final int[] out = new int[list.size()];
         Arrays.setAll(out, i -> Integer.parseInt(list.get(i)));
         return out;
      }
      
    3. Integer array to primitive int array:

      public static int[] convert(final Integer[] array)
      {
         final int[] out = new int[array.length];
         Arrays.setAll(out, i -> array[i]);
         return out;
      }
      
    4. Primitive int array to Integer array:

      public static Integer[] convert(final int[] array)
      {
         final Integer[] out = new Integer[array.length];
         Arrays.setAll(out, i -> array[i]);
         return out;
      }
      

提交回复
热议问题