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

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

    If you're using Eclipse Collections, you can use the collectInt() method to switch from an object container to a primitive int container.

    List integers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
    MutableIntList intList =
      ListAdapter.adapt(integers).collectInt(i -> i);
    Assert.assertArrayEquals(new int[]{1, 2, 3, 4, 5}, intList.toArray());
    

    If you can convert your ArrayList to a FastList, you can get rid of the adapter.

    Assert.assertArrayEquals(
      new int[]{1, 2, 3, 4, 5},
      Lists.mutable.with(1, 2, 3, 4, 5)
        .collectInt(i -> i).toArray());
    

    Note: I am a committer for Eclipse collections.

提交回复
热议问题