Come convertire int [] in Elenco in Java?


Come faccio a convertire int[] in List<Integer> in Java?

Certo, sono interessato a qualsiasi altra risposta che farlo in un ciclo, elemento per elemento. Ma se non c'è altra risposta, sceglierò quella come la migliore per mostrare il fatto che questa funzionalità non fa parte di Java.

Author: Jonik, 2009-07-02

16 answers

Non esiste una scorciatoia per la conversione da int[] a List<Integer> poiché Arrays.asList non si occupa della boxe e creerà solo un List<int[]> che non è quello che vuoi. Devi fare un metodo di utilità.

int[] ints = {1, 2, 3};
List<Integer> intList = new ArrayList<Integer>();
for (int i : ints)
{
    intList.add(i);
}
 189
Author: willcodejavaforfood, 2018-01-25 14:59:55

Flussi

In Java 8 puoi farlo

int[] ints = {1,2,3};
List<Integer> list = Arrays.stream(ints).boxed().collect(Collectors.toList());
 173
Author: mikeyreilly, 2018-09-08 00:02:01

Anche da librerie guava ... com.Google.comune.primitive.Int:

List<Integer> Ints.asList(int...)
 155
Author: louisgab, 2012-06-27 17:23:35

Array.asList non funzionerà come si aspettano alcune delle altre risposte.

Questo codice non creerà un elenco di 10 numeri interi. Stamperà 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());

Questo creerà un elenco di numeri interi:

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

Se hai già la matrice di int, non c'è un modo rapido per convertire, stai meglio con il ciclo.

D'altra parte, se il tuo array ha Oggetti, non primitive, Array.asList funzionerà:

String str[] = { "Homer", "Marge", "Bart", "Lisa", "Maggie" };
List<String> lst = Arrays.asList(str);
 66
Author: Leonel, 2009-07-02 12:11:56

Aggiungerò un'altra risposta con un metodo diverso; nessun ciclo ma una classe anonima che utilizzerà le funzionalità di 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; }
    };
}
 45
Author: Christoffer, 2016-05-01 06:29:50

Il pezzo di codice più piccolo sarebbe:

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

Dove ArrayUtils viene da commons-lang :)

 33
Author: Kannan Ekanath, 2016-05-01 06:30:30

In Java 8 con flusso:

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

O con collettori

List<Integer> list =  Arrays.stream(ints).boxed().collect(Collectors.toList());
 17
Author: user2037659, 2016-01-03 16:44:26

In Java 8 :

int[] arr = {1,2,3};
IntStream.of(arr).boxed().collect(Collectors.toList());
 12
Author: Neeraj, 2017-11-02 08:50:52

Vale anche la pena controllare questa segnalazione di bug, che è stata chiusa con la ragione "Non un difetto" e il seguente testo:

"L'autoboxing di interi array non è un comportamento specificato, per una buona ragione. Può essere proibitivo per array di grandi dimensioni."

 9
Author: Adamski, 2009-07-02 12:08:39

Dare una prova a questa classe:

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

Testcase:

List<Integer> ints = PrimitiveWrapper.ofIntegers(10, 20);
List<Double> doubles = PrimitiveWrapper.ofDoubles(10, 20);
// etc
 7
Author: dfa, 2009-07-02 12:24:36

Il colpo migliore:

**
 * 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;
    }
}
  • Supporto get e set.
  • Nessuna duplicazione di dati di memoria.
  • Nessuna perdita di tempo nei loop.

Esempi:

int[] intArray = new int[]{1, 2, 3};
List<Integer> integerListWrap = new IntegerListWrap(intArray);
List<Integer> integerListWrap1 = new IntegerListWrap(1, 2, 3);
 4
Author: Daniel De León, 2016-05-01 06:32:13

Se sei aperto all'utilizzo di una libreria di terze parti, questo funzionerà in Eclipse Collections :

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: sono un committer per Eclipse Collections .

 1
Author: Donald Raab, 2017-04-01 00:49:28

Ecco una soluzione:

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

Uscita:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 1
Author: Amitabha Roy, 2018-04-20 09:40:00

Ecco un modo generico per convertire array in 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;
}

Utilizzo

ArrayList<Integer> list = toArrayList(new int[]{1,2,3}, Integer.class);
 0
Author: Ilya Gazman, 2016-01-30 07:15:57
   /* 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);
 0
Author: Uddhav Gautam, 2017-08-16 18:23:26

Che dire di questo:

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

 0
Author: humblefoolish, 2018-03-23 17:31:10