Java – How to convert a primitive Array to List

Code snippets to convert a primitive array int[] to a List<Integer> :

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

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

for (int i : number) {

list.add(i);

}

In Java 8, you can use the Stream APIs to do the boxing and conversion like this :

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

1. Classic Example

Full example to convert a primitive Array to a List.

ArrayExample1.java

package com.mkyong.array;

import java.util.ArrayList;

import java.util.List;

public class ArrayExample1 {

public static void main(String[] args) {

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

List<Integer> list = convertIntArrayToList(number);

System.out.println("list : " + list);

}

private static List<Integer> convertIntArrayToList(int[] input) {

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

for (int i : input) {

list.add(i);

}

return list;

}

}

Output

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

Note

You can’t use the popular Arrays.asList to convert it directly, because boxing issue.

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

// No, the return type is not what we want

List<int[]> ints = Arrays.asList(number);

2. Java 8 Stream

Full Java 8 stream example to convert a primitive Array to a List.

ArrayExample2.java

package com.mkyong.array;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.List;

import java.util.stream.Collectors;

import java.util.stream.IntStream;

public class ArrayExample2 {

public static void main(String[] args) {

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

// IntStream.of or Arrays.stream, same output

//List<Integer> list = IntStream.of(number).boxed().collect(Collectors.toList());


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

System.out.println("list : " + list);

}

}

Output

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

 

from:http://www.mkyong.com/java/java-how-to-convert-a-primitive-array-to-list/


此随笔或为自己所写、或为转载于网络。仅用于个人收集及备忘。