I once asked this question to one of the Java developers during an Interview and like many others, he answered that Arrays.asList() can convert an array of primitive integer values to ArrayList<Integer> in Java, which was actually wrong. Even though, Arrays.asList() is the go-to method to convert an Array to ArrayList in Java when it comes to converting a primitive array to ArrayList, this method is not useful. The Arrays.asList() method does not deal with boxing and it will just create a List<int[]> which is not what you want. In fact, there was no shortcut to convert an int[] to ArrayList<Integer> or long[] to ArrayList<Long> till Java 8.
From JDK 8 onwards, you either had to make a utility method or need to use general-purpose Java libraries like Google Guava or Apache Commons to convert an array of primitive values. byte, short, char, int, long, float, and double to ArrayList of Byte, Character, Short, Integer, Long, Float, and Double wrapper classes.
Though from Java 8 onwards, you can use the java.util.Stream to convert an int[] to ArrayList<Integer>. There are specialized stream implementations for primitive data types like IntStream for primitive int, LongStream for primitive long, and DoubleStream for primitive double, which can convert an array of primitive values to a stream of primitive values.
Once you get the Stream of int values, you can use the boxed() method to convert it to Stream of Integer wrapper objects. After that you can just convert Stream to List as shown in that article i.e. you can use the collect() method of the stream with Collectors.toList() to get a list.
Alternatively, you can also use the copy constructor of the Collection interface to create an ArrayList by copying all elements from the List instance as shown in the following example:
What is this code doing? Well, if you are not very familiar with Java 8, Stream, and method reference then here is a step by step explanation of the above one-liner of converting a primitive array to ArrayList in JDK 8:
1) The IntStream.of(primes) is converting an int array to an IntStream object.
2) The boxed() method of IntStream convert applies boxing on each element of IntStream and returns a Stream of Integer i.e it converts IntStream to Stream<Integer> object.
3) The collect() method collects all elements of Stream into any Collection class by using Collectors of Java 8. A Collector encapsulates the functions used as arguments to collect(Supplier, BiConsumer, BiConsumer), allowing for reuse of collection strategies and composition of collect operations such as multiple-level grouping or partitioning.
4) The Collectors.toCollection() method collects elements of Stream into a Collection which is specified by the first parameter. Here we are passing ArrayList::new which is a constructor reference, which means all elements of Stream will be collected into an ArrayList. See The Complete Java MasterClass to learn more.
From JDK 8 onwards, you either had to make a utility method or need to use general-purpose Java libraries like Google Guava or Apache Commons to convert an array of primitive values. byte, short, char, int, long, float, and double to ArrayList of Byte, Character, Short, Integer, Long, Float, and Double wrapper classes.
Though from Java 8 onwards, you can use the java.util.Stream to convert an int[] to ArrayList<Integer>. There are specialized stream implementations for primitive data types like IntStream for primitive int, LongStream for primitive long, and DoubleStream for primitive double, which can convert an array of primitive values to a stream of primitive values.
Once you get the Stream of int values, you can use the boxed() method to convert it to Stream of Integer wrapper objects. After that you can just convert Stream to List as shown in that article i.e. you can use the collect() method of the stream with Collectors.toList() to get a list.
int[] to List
If you want ArrayList instead of List then you can pass a Supplier to Collectors, which will accumulate elements into an ArrayList as shown below:int[] primes = new int[]{2, 3, 5, 7, 11, 13, 17};
ArrayList<Integer> list = IntStream.of(primes)
.boxed()
.collect(Collectors.toCollection(ArrayList::new));
Alternatively, you can also use the copy constructor of the Collection interface to create an ArrayList by copying all elements from the List instance as shown in the following example:
List<Integer> list = IntStream.of(primes)
.boxed()
.collect(Collectors.toList());
ArrayList<Integer> arraylist = new ArrayList<>(list);
What is this code doing? Well, if you are not very familiar with Java 8, Stream, and method reference then here is a step by step explanation of the above one-liner of converting a primitive array to ArrayList in JDK 8:
1) The IntStream.of(primes) is converting an int array to an IntStream object.
2) The boxed() method of IntStream convert applies boxing on each element of IntStream and returns a Stream of Integer i.e it converts IntStream to Stream<Integer> object.
3) The collect() method collects all elements of Stream into any Collection class by using Collectors of Java 8. A Collector encapsulates the functions used as arguments to collect(Supplier, BiConsumer, BiConsumer), allowing for reuse of collection strategies and composition of collect operations such as multiple-level grouping or partitioning.
4) The Collectors.toCollection() method collects elements of Stream into a Collection which is specified by the first parameter. Here we are passing ArrayList::new which is a constructor reference, which means all elements of Stream will be collected into an ArrayList. See The Complete Java MasterClass to learn more.
How to convert int[] to ArrayList of Integer in Java 8
By far, That was the simplest way to convert an array of primitive data types to a List of wrapper objects like an array of ints to ArrayList of Integers.Btw, there is another way to convert a primitive array to ArrayList in Java 8 by using the Arrays.stream() method, which converts an array to Stream in Java 8.
This method is equivalent to IntStream.of(int[]) and return an IntStream. The rest of the code will remain the same i.e. you can use the following one-liner to convert an int[] to ArrayList in JDK 8:
From the output, it's clear that both ways of converting an array of primitive values to ArrayList of objects work fine. You can use whatever you want. See From Collections to Streams in Java 8 Using Lambda Expressions to learn more.
The code is pretty simple and self-explanatory. We are iterating over ArrayList using enhanced for loop of Java 5 and adding each int value from array to ArrayList. When you add, Java uses autoboxing to convert an int value to an Integer object, so in the end, you have an ArrayList of Integer. Though, you can also use other ways to loop over an array, like by using for or while loop.
One slightly important thing to note is initializing ArrayList with the length of the array. This prevents ArrayList from being resizing multiple times.
If you remember, by default ArrayList initializes with 10 elements and then keeps resize when it is about to fill, I guess when the load factor grows up to 0.75 it resizes and doubles itself. This involves a lot of array copy, which can slow down your application.
It's also a Java collection best practice to provide size while creating an instance of any Collection class like ArrayList. See these Java Performance courses for more such tips.
That's all about how to convert an int[] to ArrayList<Integer> in Java. You can use this technique to convert any primitive array to ArrayList of respective wrapper class like you can convert a long[] to ArrayList<Long>, a float[] to ArrayList<Float>, a double[] to ArrayList<Double>, a char[] to ArrayList<Character>, a short[] to ArrayList<Short>, and a byte[] to ArrayList<Byte> in Java.
Related Java 8 Tutorials
If you are interested in learning more about the new features of Java 8, here are my earlier articles covering some of the important concepts of Java 8:
ArrayList<Integer> list = Arrays.stream(ints)
.boxed()
.collect(Collectors.toCollection(ArrayList::new));
Java Program to convert int Array to ArrayList of Integer in Java
Here is the full Java program to convert an int[] to ArrayList<Integer> in Java 8:import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/*
* Java Program to convert a long[] to ArrayList<Long> in JDK 8
*/
public class Main {
public static void main(String[] args) throws Exception {
// converting an array of Integer to ArrayList of Integer
int[] primes = new int[]{2, 3, 5, 7, 11, 13, 17};
System.out.println("primitive int array: " + Arrays.toString(primes));
ArrayList<Integer> listOfInts = IntStream.of(primes)
.boxed()
.collect(Collectors.toCollection(ArrayList::new));
System.out.println("ArrayList<Integer> : " + listOfInts);
long[] numbers = new long[]{202, 3003, 2002, 3003, 222};
ArrayList<Long> listOfLong = Arrays.stream(numbers)
.boxed()
.collect(Collectors.toCollection(ArrayList::new));
System.out.println("primitive long array: " + Arrays.toString(numbers));
System.out.println("ArrayList<Long> : " + listOfLong);
}
}
Output:
primitive int array: [2, 3, 5, 7, 11, 13, 17]
ArrayList<Integer> : [2, 3, 5, 7, 11, 13, 17]
primitive long array: [202, 3003, 2002, 3003, 222]
ArrayList<Long> : [202, 3003, 2002, 3003, 222]
From the output, it's clear that both ways of converting an array of primitive values to ArrayList of objects work fine. You can use whatever you want. See From Collections to Streams in Java 8 Using Lambda Expressions to learn more.
How to convert int[] to ArrayList of Integer in Java 6,7
If you are not running in Java 8 and want to convert int[] to ArrayList<> on an earlier version of Java, like JDK 6 and JDK 7, then you have two choices, either use Google's Guava or Apache commons library as shown here or write your own conversion method as shown below:/*
* Java Program to convert int[] to ArrayList<Integer>
*/
public class Main {
public static void main(String[] args) throws Exception {
int[] primes = new int[]{2, 3, 5, 7, 11, 13, 17};
System.out.println("primitive int array: " + Arrays.toString(primes));
ArrayList<Integer> listOfInts = new ArrayList<>(primes.length);
for(int i: primes){
listOfInts.add(i);
}
System.out.println("ArrayList<Integer> : " + listOfInts);
}
}
Output
primitive int array: [2, 3, 5, 7, 11, 13, 17]
ArrayList<Integer> : [2, 3, 5, 7, 11, 13, 17]
The code is pretty simple and self-explanatory. We are iterating over ArrayList using enhanced for loop of Java 5 and adding each int value from array to ArrayList. When you add, Java uses autoboxing to convert an int value to an Integer object, so in the end, you have an ArrayList of Integer. Though, you can also use other ways to loop over an array, like by using for or while loop.
One slightly important thing to note is initializing ArrayList with the length of the array. This prevents ArrayList from being resizing multiple times.
If you remember, by default ArrayList initializes with 10 elements and then keeps resize when it is about to fill, I guess when the load factor grows up to 0.75 it resizes and doubles itself. This involves a lot of array copy, which can slow down your application.
It's also a Java collection best practice to provide size while creating an instance of any Collection class like ArrayList. See these Java Performance courses for more such tips.
That's all about how to convert an int[] to ArrayList<Integer> in Java. You can use this technique to convert any primitive array to ArrayList of respective wrapper class like you can convert a long[] to ArrayList<Long>, a float[] to ArrayList<Float>, a double[] to ArrayList<Double>, a char[] to ArrayList<Character>, a short[] to ArrayList<Short>, and a byte[] to ArrayList<Byte> in Java.
Related Java 8 Tutorials
If you are interested in learning more about the new features of Java 8, here are my earlier articles covering some of the important concepts of Java 8:
- How to join String in Java 8 (example)
- How to use forEach() method in Java 8 (example)
- How to use filter() method in Java 8 (tutorial)
- 5 Books to Learn Java 8 from Scratch (books)
- Java 8 - Stream.collect() Example (example)
- How to use Stream class in Java 8 (tutorial)
- What is the double-colon operator of Java 8? (tutorial)
- How to join String in Java 8 (example)
- 20 Examples of Date and Time in Java 8 (tutorial)
- 10 Free Courses for Experienced Java Programmers (courses)
- How to use peek() method in Java 8 (example)
- Java 8 Stream.findFirst() + filter() example (see)
- How to sort the may by values in Java 8? (example)
- How to convert List to Map in Java 8 (solution)
- Difference between abstract class and interface in Java 8? (answer)
- How to use peek() method in Java 8 (example)
- How to format/parse the date with LocalDateTime in Java 8? (tutorial)
- 5 Free Courses to learn Java 8 and 9 (courses)
Thanks a lot for reading this article so far. If you like this article then please share it with your friends and colleagues. If you have any questions or feedback then please drop a comment.
P. S. - In general, you should use Stream if you are using Java 8, it's cleaner than the Java 6 approach and also takes just one line to convert a primitive array to ArrayList. If you don't know much about Stream and Java 8, I suggest you read a good book on Java 8 to learn more about IntStream and other Stream features like Java 8 in Action.
No comments:
Post a Comment
Feel free to comment, ask questions if you have any doubt.