Cómo convertir una ArrayList que contiene enteros a matriz int primitiva?


Estoy tratando de convertir una ArrayList que contiene objetos Enteros a primitive int [] con la siguiente pieza de código, pero está lanzando un error de tiempo de compilación. Es posible convertir en Java?

List<Integer> x =  new ArrayList<Integer>();
int[] n = (int[])x.toArray(int[x.size()]);
Author: Jonas, 2009-04-05

12 answers

Puedes convertir, pero no creo que haya nada incorporado para hacerlo automáticamente:

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;
}

(Tenga en cuenta que esto lanzará una excepción NullPointerException si integers o cualquier elemento dentro de él es null.)

EDITAR: Según los comentarios, es posible que desee utilizar el iterador de listas para evitar costos desagradables con listas como 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;
}
 188
Author: Jon Skeet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-12 17:40:09

Si está utilizando java-8 también hay otra forma de hacer esto.

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

Lo que hace es:

  • obteniendo un Stream<Integer> de la lista
  • obteniendo un IntStream asignando cada elemento a sí mismo (función de identidad), deshaciendo el valor int retenido por cada objeto Integer (hecho automáticamente desde Java 5)
  • obteniendo el array de int llamando a toArray

También puede llamar explícitamente a intValue a través de una referencia de método, i. e:

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

También vale la pena mencionar que podría obtener un NullPointerException si tiene alguna referencia null en la lista. Esto podría evitarse fácilmente agregando una condición de filtrado a la tubería de flujo como esta:

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

Ejemplo:

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]
 131
Author: Alexis C.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-19 17:49:17

Apache Commons tiene una clase ArrayUtils, que tiene un método ToPrimitive() que hace exactamente esto.

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]));

Sin embargo, como Jon mostró, es bastante fácil hacer esto por ti mismo en lugar de usar bibliotecas externas.

 59
Author: Björn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-04-05 09:00:32

Google Guayaba

Google Guava proporciona una manera ordenada de hacer esto llamando Ints.toArray.

List<Integer> list = ...;
int[] values = Ints.toArray(list);
 52
Author: Snehal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-29 20:43:40

Creo que iterar usando el iterador de la Lista es una mejor idea, ya que list.get(i) puede tener un rendimiento pobre dependiendo de la implementación de la Lista:

private int[] buildIntArray(List<Integer> integers) {
    int[] ints = new int[integers.size()];
    int i = 0;
    for (Integer n : integers) {
        ints[i++] = n;
    }
    return ints;
}
 40
Author: Matthew Willis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-11 18:56:59

Usar Dollar debería ser bastante simple:

List<Integer> list = $(5).toList(); // the list 0, 1, 2, 3, 4  
int[] array = $($(list).toArray()).toIntArray();

Estoy planeando mejorar el DSL para eliminar la llamada intermedia toArray()

 6
Author: dfa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-01 20:14:28

Si está utilizando Colecciones de Eclipse, puede usar el método collectInt() para cambiar de un contenedor de objetos a un contenedor int primitivo.

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());

Si puede convertir su ArrayList a un FastList, puede deshacerse del adaptador.

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

Nota: Soy un committer para las colecciones de Eclipse.

 3
Author: Craig P. Motlin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-05 03:15:54

Me desconcierta que alentemos métodos personalizados únicos siempre que una biblioteca perfectamente buena y bien utilizada como Apache Commons ya haya resuelto el problema. Aunque la solución es trivial si no absurda, es irresponsable fomentar tal comportamiento debido al mantenimiento y la accesibilidad a largo plazo.

Simplemente vaya con Apache Commons

 1
Author: Andrew F.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-18 18:19:56

Simplemente puede copiarlo en un array:

int[] arr = new int[list.size()];
for(int i = 0; i < list.size(); i++) {
    arr[i] = list.get(i);
}

No es demasiado elegante; pero, bueno, funciona...

 1
Author: sagiksp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-13 15:28:26

Este segmento de código está funcionando para mí, pruebe esto

Integer[] arr = x.toArray(new Integer[x.size()]);
 0
Author: user3444748,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-07 17:52:07
   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());
    }
 -4
Author: CodeMadness,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-03 12:49:07
Integer[] arr = (Integer[]) x.toArray(new Integer[x.size()]);

Acceso arr como normal int[].

 -6
Author: snn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-09-14 20:22:04