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
In Java 8 you can do this
int[] ints = {1,2,3};
List<Integer> list = Arrays.stream(ints).boxed().collect(Collectors.toList());
The smallest piece of code would be:
public List<Integer> myWork(int[] array) {
return Arrays.asList(ArrayUtils.toObject(array));
}
where ArrayUtils comes from commons-lang :)
int[] arr = { 1, 2, 3, 4, 5 };
List<Integer> list = Arrays.stream(arr) // IntStream
.boxed() // Stream<Integer>
.collect(Collectors.toList());
see this
If you're open to using a third party library, this will work 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);
Note: I am a committer for Eclipse Collections.
The best shot:
**
* 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;
}
}
Examples:
int[] intArray = new int[]{1, 2, 3};
List<Integer> integerListWrap = new IntegerListWrap(intArray);
List<Integer> integerListWrap1 = new IntegerListWrap(1, 2, 3);
I'll add another answer with a different method; no loop but an anonymous class that will utilize the autoboxing features:
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; }
};
}