Reputation: 287770
How do I convert int[]
into List<Integer>
in Java?
Of course, I'm interested in any other answer than doing it in a loop, item by item. But if there's no other answer, I'll pick that one as the best to show the fact that this functionality is not part of Java.
Upvotes: 594
Views: 819465
Reputation: 69
The traditional way of adding elements from an Array to the List
List<Integer> traditionalList = new ArrayList<>();
for(int i: nums) {
traditionalList.add(i);
}
System.out.println("Traditional way of adding elements from array to list: " + traditionalList);
Using Stream.collect():
List<Integer> intList = Arrays.stream(nums).boxed().collect(Collectors.toList()); // Using Collectors stream and Arrays.stream()
List<Integer> intList1 =IntStream.of(nums).boxed().collect(Collectors.toList()); // Using Collectors stream and IntStream.of()
System.out.println("Using Stream.collect(): " + intList + " \t" + intList1);
Using Stream.toArray()
List<Integer> collectionIntList = new ArrayList<>();
Collections.addAll(collectionIntList, Arrays.stream(nums).boxed().toArray(Integer[]::new)); // Returns Integer[], addAll to new List
System.out.println("Using Stream.toArray() and new keyword" + collectionIntList); //using toArray
Upvotes: 1
Reputation: 429
What about this:
int[] a = {1,2,3};
Integer[] b = ArrayUtils.toObject(a);
List<Integer> c = Arrays.asList(b);
Upvotes: 4
Reputation: 13679
The best shot:
/**
* Integer modifiable fixed 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);
Upvotes: 6
Reputation: 121
You could use IntStream of and boxed it to Integer after that sorted using reverseOrder comparator.
List<Integer> listItems = IntStream.of(arrayItems)
.boxed()
.sorted(Collections.reverseOrder())
.collect(Collectors.toList());
This approach has the advantage of being more flexible, as you can use different collectors to create different types of lists (e.g., an ArrayList, a LinkedList, etc.).
Upvotes: 2
Reputation: 6923
int
array. Call either Arrays.stream
or IntStream.of
.IntStream#boxed
to use boxing conversion from int
primitive to Integer
objects.Stream.collect( Collectors.toList() )
. Or more simply in Java 16+, call Stream#toList()
.Example:
int[] ints = {1,2,3};
List<Integer> list = Arrays.stream(ints).boxed().collect(Collectors.toList());
In Java 16 and later:
List<Integer> list = Arrays.stream(ints).boxed().toList();
Upvotes: 589
Reputation: 707
int[] arr = { 1, 2, 3, 4, 5 };
List<Integer> list = Arrays.stream(arr) // IntStream
.boxed() // Stream<Integer>
.collect(Collectors.toList());
see this
Upvotes: 10
Reputation: 44093
There is no shortcut for converting from int[]
to List<Integer>
as Arrays.asList
does not deal with boxing and will just create a List<int[]>
which is not what you want. You have to make a utility method.
int[] ints = {1, 2, 3};
List<Integer> intList = new ArrayList<Integer>(ints.length);
for (int i : ints)
{
intList.add(i);
}
Upvotes: 353
Reputation: 1647
If you are using java 8, we can use the stream API to convert it into a list.
List<Integer> list = Arrays.stream(arr) // IntStream
.boxed() // Stream<Integer>
.collect(Collectors.toList());
You can also use the IntStream to convert as well.
List<Integer> list = IntStream.of(arr) // return Intstream
.boxed() // Stream<Integer>
.collect(Collectors.toList());
There are other external library like guava and apache commons also available convert it.
cheers.
Upvotes: 23
Reputation: 23820
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]));
}
Upvotes: 4
Reputation: 797
Here is a solution:
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);
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Upvotes: 2
Reputation: 2557
In Java 8 :
int[] arr = {1,2,3};
IntStream.of(arr).boxed().collect(Collectors.toList());
Upvotes: 24
Reputation: 7636
/* 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);
Upvotes: 2
Reputation: 6706
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.
Upvotes: 2
Reputation: 17621
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 :)
Upvotes: 47
Reputation: 12910
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; }
};
}
Upvotes: 57
Reputation: 32271
Here is a generic way to convert array to 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;
}
Usage
ArrayList<Integer> list = toArrayList(new int[]{1,2,3}, Integer.class);
Upvotes: 1
Reputation: 491
In Java 8 with stream:
int[] ints = {1, 2, 3};
List<Integer> list = new ArrayList<Integer>();
Collections.addAll(list, Arrays.stream(ints).boxed().toArray(Integer[]::new));
or with Collectors
List<Integer> list = Arrays.stream(ints).boxed().collect(Collectors.toList());
Upvotes: 37
Reputation: 2414
Also from guava libraries... com.google.common.primitives.Ints:
List<Integer> Ints.asList(int...)
Upvotes: 194
Reputation: 116412
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
Upvotes: 8
Reputation: 29217
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);
Upvotes: 116
Reputation: 54725
It's also worth checking out this bug report, which was closed with reason "Not a defect" and the following text:
"Autoboxing of entire arrays is not specified behavior, for good reason. It can be prohibitively expensive for large arrays."
Upvotes: 13