How do I convert int[]
into List
in Java?
Of course, I\'m interested in any other answer than doing it in a loop, item by it
/* 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);
What about this:
int[] a = {1,2,3};
Integer[] b = ArrayUtils.toObject(a);
List<Integer> c = Arrays.asList(b);
Arrays.asList will not work as some of the other answers expect.
This code will not create a list of 10 integers. It will print 1, not 10:
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
List lst = Arrays.asList(arr);
System.out.println(lst.size());
This will create a list of integers:
List<Integer> lst = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
If you already have the array of ints, there is not quick way to convert, you're better off with the loop.
On the other hand, if your array has Objects, not primitives in it, Arrays.asList will work:
String str[] = { "Homer", "Marge", "Bart", "Lisa", "Maggie" };
List<String> lst = Arrays.asList(str);
give a try to this class:
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
Here is another possibility, again with Java 8 Streams:
void intArrayToListOfIntegers(int[] arr, List<Integer> list) {
IntStream.range(0, arr.length).forEach(i -> list.add(arr[i]));
}
Here is my 2 cents:
Queue<int[]> q = new LinkedList<int[]>();
q.add(new int[]{1,2})