Pregunta

¿Cómo convierto en int[] List<Integer> en Java?

Por supuesto, estoy interesado en ninguna otra respuesta que hacerlo en un bucle, punto por punto. Pero si no hay otra respuesta, voy a recoger que uno como el mejor para mostrar el hecho de que esta funcionalidad no es parte de Java.

¿Fue útil?

Solución

No hay atajo para la conversión de int[] a List<Integer> como Arrays.asList no trata con el boxeo y se acaba de crear un List<int[]> que no es lo que desea. Usted tiene que hacer un método de utilidad.

int[] ints = {1, 2, 3};
List<Integer> intList = new ArrayList<Integer>();
for (int i : ints)
{
    intList.add(i);
}

Otros consejos

Streams

En Java 8 se puede hacer esto

int[] ints = {1,2,3};
List<Integer> list = Arrays.stream(ints).boxed().collect(Collectors.toList());

También desde bibliotecas de guayaba ... com.google.common.primitives.Ints:

List<Integer> Ints.asList(int...)

Arrays.asList no funcionará como algunas de las otras respuestas esperan.

Este código no crear una lista de 10 números enteros. Se imprimirá 1 , no 10

int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
List lst = Arrays.asList(arr);
System.out.println(lst.size());

Esto creará una lista de números enteros:

List<Integer> lst = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

Si ya tiene la matriz de enteros, no hay forma rápida de convertir, es mejor con el bucle.

Por otro lado, si la matriz tiene objetos, no primitivas en ella, Arrays.asList funcionará:

String str[] = { "Homer", "Marge", "Bart", "Lisa", "Maggie" };
List<String> lst = Arrays.asList(str);

Voy a añadir otra respuesta con un método diferente; pero sin lazo de una clase anónima que utilizará las características autoboxing:

public List<Integer> asList(final int[] is)
{
    return new AbstractList<Integer>() {
            public Integer get(int i) { return is[i]; }
            public int size() { return is.length; }
    };
}

La pieza más pequeña de código sería:

public List<Integer> myWork(int[] array) {
    return Arrays.asList(ArrayUtils.toObject(array));
}

donde ArrayUtils proviene de commons-lang:)

En Java 8 con la corriente:

int[] ints = {1, 2, 3};
List<Integer> list = new ArrayList<Integer>();
Collections.addAll(list, Arrays.stream(ints).boxed().toArray(Integer[]::new));

o con los colectores

List<Integer> list =  Arrays.stream(ints).boxed().collect(Collectors.toList());

En Java 8:

int[] arr = {1,2,3};
IntStream.of(arr).boxed().collect(Collectors.toList());

Es también vale la pena mirar este informe de error, que estaba cerrada con la razón "No es un defecto" y el texto siguiente:

"Autoboxing de arrays enteros no se especifica el comportamiento, por una buena razón. Puede ser prohibitivamente caro para grandes conjuntos ".

darle una oportunidad a esta clase:

class PrimitiveWrapper<T> extends AbstractList<T> {

    private final T[] data;

    private PrimitiveWrapper(T[] data) {
        this.data = data; // you can clone this array for preventing aliasing
    }

    public static <T> List<T> ofIntegers(int... data) {
        return new PrimitiveWrapper(toBoxedArray(Integer.class, data));
    }

    public static <T> List<T> ofCharacters(char... data) {
        return new PrimitiveWrapper(toBoxedArray(Character.class, data));
    }

    public static <T> List<T> ofDoubles(double... data) {
        return new PrimitiveWrapper(toBoxedArray(Double.class, data));
    }  

    // ditto for byte, float, boolean, long

    private static <T> T[] toBoxedArray(Class<T> boxClass, Object components) {
        final int length = Array.getLength(components);
        Object res = Array.newInstance(boxClass, length);

        for (int i = 0; i < length; i++) {
            Array.set(res, i, Array.get(components, i));
        }

        return (T[]) res;
    }

    @Override
    public T get(int index) {
        return data[index];
    }

    @Override
    public int size() {
        return data.length;
    }
}

caso_prueba:

List<Integer> ints = PrimitiveWrapper.ofIntegers(10, 20);
List<Double> doubles = PrimitiveWrapper.ofDoubles(10, 20);
// etc

El mejor tiro:

**
 * Integer modifiable fix length list of an int array or many int's.
 *
 * @author Daniel De Leon.
 */
public class IntegerListWrap extends AbstractList<Integer> {

    int[] data;

    public IntegerListWrap(int... data) {
        this.data = data;
    }

    @Override
    public Integer get(int index) {
        return data[index];
    }

    @Override
    public Integer set(int index, Integer element) {
        int r = data[index];
        data[index] = element;
        return r;
    }

    @Override
    public int size() {
        return data.length;
    }
}
  • Soporte obtener y definir.
  • No hay duplicación de datos de memoria.
  • No perder el tiempo en los bucles.

Ejemplos:

int[] intArray = new int[]{1, 2, 3};
List<Integer> integerListWrap = new IntegerListWrap(intArray);
List<Integer> integerListWrap1 = new IntegerListWrap(1, 2, 3);

Si está utilizando Java 8, podemos utilizar la API de flujo para convertirlo en una lista.

List<Integer> list = Arrays.stream(arr)     // IntStream 
                                .boxed()        // Stream<Integer>
                                .collect(Collectors.toList());

También puede utilizar el IntStream para convertir así.

List<Integer> list = IntStream.of(arr) // return Intstream
                                    .boxed()        // Stream<Integer>
                                    .collect(Collectors.toList());

Hay otra biblioteca externa como la guayaba y Apache Commons  también disponible convertirlo.

aplausos.

Si usted está abierto al uso de una biblioteca de terceros, esto va a funcionar en Eclipse Colecciones :

int[] a = {1, 2, 3};
List<Integer> integers = IntLists.mutable.with(a).collect(i -> i);
Assert.assertEquals(Lists.mutable.with(1, 2, 3), integers);

Nota:. Soy un confirmador para Eclipse Colecciones

   /* Integer[] to List<Integer> */



        Integer[] intArr = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
        List<Integer> arrList = new ArrayList<>();
        arrList.addAll(Arrays.asList(intArr));
        System.out.println(arrList);


/* Integer[] to Collection<Integer> */


    Integer[] intArr = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
    Collection<Integer> c = Arrays.asList(intArr);

¿Qué hay de esto:

int[] a = {1,2,3}; Integer[] b = ArrayUtils.toObject(a); List<Integer> c = Arrays.asList(b);

Aquí es una solución:

int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

Integer[] iArray = Arrays.stream(array).boxed().toArray(Integer[]::new);
System.out.println(Arrays.toString(iArray));

List<Integer> list = new ArrayList<>();
Collections.addAll(list, iArray);
System.out.println(list);

Salida:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Aquí hay otra posibilidad, de nuevo con Java 8 secuencias:

void intArrayToListOfIntegers(int[] arr, List<Integer> list) {
    IntStream.range(0, arr.length).forEach(i -> list.add(arr[i]));
}

Aquí está una manera genérica para convertir matriz a ArrayList

<T> ArrayList<T> toArrayList(Object o, Class<T> type){
    ArrayList<T> objects = new ArrayList<>();
    for (int i = 0; i < Array.getLength(o); i++) {
        //noinspection unchecked
        objects.add((T) Array.get(o, i));
    }
    return objects;
}

Uso

ArrayList<Integer> list = toArrayList(new int[]{1,2,3}, Integer.class);

Me pregunto si algo en la línea de Arrays.asList(...array) funcionaría ...

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top