Java 如何将包含整数的 ArrayList 转换为原始 int 数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/718554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 18:42:14  来源:igfitidea点击:

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

javaarraysarraylistprimitive-types

提问by Snehal

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 convert in Java?

我正在尝试使用以下代码将包含 Integer 对象的 ArrayList 转换为原始 int[] ,但它引发了编译时错误。是否可以在 Java 中进行转换?

List<Integer> x =  new ArrayList<Integer>();
int[] n = (int[])x.toArray(int[x.size()]);

采纳答案by Jon Skeet

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 integersor any element within it is null.)

(请注意,如果其中一个integers或任何元素是,这将抛出 NullPointerException null。)

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

编辑:根据评论,您可能希望使用列表迭代器来避免使用列表的令人讨厌的成本,例如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;
}

回答by Bj?rn

Apache Commons has a ArrayUtils class, which has a method toPrimitive() that does exactly this.

Apache Commons 有一个 ArrayUtils 类,它有一个方法 toPrimitive() 就是这样做的。

import org.apache.commons.lang.ArrayUtils;
...
    List<Integer> list = new ArrayList<Integer>();
    list.add(new Integer(1));
    list.add(new Integer(2));
    int[] intArray = ArrayUtils.toPrimitive(list.toArray(new Integer[0]));

However, as Jon showed, it is pretty easy to do this by yourself instead of using external libraries.

但是,正如 Jon 所展示的那样,您可以很容易地自己完成此操作,而无需使用外部库。

回答by dfa

using Dollarshould be quite simple:

使用Dollar应该很简单:

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

我计划改进 DSL 以删除中间toArray()调用

回答by Andrew F.

It bewilders me that we encourage one-off custom methods whenever a perfectly good, well used library like Apache Commons has solved the problem already. Though the solution is trivial if not absurd, it is irresponsible to encourage such a behavior due to long term maintenance and accessibility.

令我感到困惑的是,只要像 Apache Commons 这样非常好的、使用良好的库已经解决了这个问题,我们就会鼓励一次性的自定义方法。尽管解决方案即使不荒谬也微不足道,但由于长期维护和可访问性,鼓励这种行为是不负责任的。

Just go with Apache Commons

只需使用Apache Commons

回答by Matthew Willis

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:

我相信使用 List 的迭代器进行迭代是一个更好的主意,因为list.get(i)根据 List 实现可能会有很差的性能:

private int[] buildIntArray(List<Integer> integers) {
    int[] ints = new int[integers.size()];
    int i = 0;
    for (Integer n : integers) {
        ints[i++] = n;
    }
    return ints;
}

回答by snn

Integer[] arr = (Integer[]) x.toArray(new Integer[x.size()]);

access arrlike normal int[].

arr正常访问int[]

回答by Snehal

Google Guava

谷歌番石榴

Google Guavaprovides a neat way to do this by calling Ints.toArray.

Google Guava通过调用Ints.toArray.

List<Integer> list = ...;
int[] values = Ints.toArray(list);

回答by CodeMadness

   List<Integer> list = new ArrayList<Integer>();

    list.add(1);
    list.add(2);

    int[] result = null;
    StringBuffer strBuffer = new StringBuffer();
    for (Object o : list) {
        strBuffer.append(o);
        result = new int[] { Integer.parseInt(strBuffer.toString()) };
        for (Integer i : result) {
            System.out.println(i);
        }
        strBuffer.delete(0, strBuffer.length());
    }

回答by Craig P. Motlin

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

如果您使用Eclipse Collections,则可以使用该collectInt()方法从对象容器切换到原始 int 容器。

List<Integer> 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 ArrayListto a FastList, you can get rid of the adapter.

如果您可以将您的转换ArrayList为 a FastList,则可以摆脱适配器。

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.

注意:我是 Eclipse 集合的提交者。

回答by Alexis C.

If you are using java-8there's also another way to do this.

如果您使用的是java-8,还有另一种方法可以做到这一点。

int[] arr = list.stream().mapToInt(i -> i).toArray();

What it does is:

它的作用是:

  • getting a Stream<Integer>from the list
  • obtaining an IntStreamby mapping each element to itself (identity function), unboxing the intvalue hold by each Integerobject (done automatically since Java 5)
  • getting the array of intby calling toArray
  • Stream<Integer>从列表中获取
  • IntStream通过将每个元素映射到自身(身份函数)来获取一个,将每个对象int持有的值拆箱Integer(自 Java 5 以来自动完成)
  • int通过调用获取数组toArray

You could also explicitly call intValuevia a method reference, i.e:

您还可以intValue通过方法引用显式调用,即:

int[] arr = list.stream().mapToInt(Integer::intValue).toArray();

It's also worth mentioning that you could get a NullPointerExceptionif you have any nullreference in the list. This could be easily avoided by adding a filtering condition to the stream pipeline like this:

还值得一提的是,NullPointerException如果您null在列表中有任何参考,您可以获得一个。这可以通过向流管道添加过滤条件来轻松避免,如下所示:

                       //.filter(Objects::nonNull) also works
int[] arr = list.stream().filter(i -> i != null).mapToInt(i -> i).toArray();

Example:

例子:

List<Integer> list = Arrays.asList(1, 2, 3, 4);
int[] arr = list.stream().mapToInt(i -> i).toArray(); //[1, 2, 3, 4]

list.set(1, null); //[1, null, 3, 4]
arr = list.stream().filter(i -> i != null).mapToInt(i -> i).toArray(); //[1, 3, 4]