How can I convert an array to a list in Java?

How can I convert an array to a list in Java?

I’ve used Arrays.asList(), but I’ve noticed that its behavior and signature changed from Java SE 1.4.2 to 8. Most of the examples I’ve found online use the 1.4.2 behavior.

For instance, in 1.4.2:

int[] numbers = new int[] { 1, 2, 3 };
Arrays.asList(numbers);

would return a list containing the elements 1, 2, 3, but in 1.5.0+ it returns a list containing the array numbers.

While in many cases, this difference is easy to detect, sometimes it can slip unnoticed, as in:

Assert.assertTrue(Arrays.asList(numbers).indexOf(4) == -1);

Can anyone provide a solution or workaround for this issue?

Hey,

In the provided example, the issue arises because you cannot have a List of a primitive type like int. Instead, you should use the Integer class, which wraps the int primitive, to create a List.

Here’s how you can convert your array to a List using the Arrays.asList utility method:

Integer[] numbers = new Integer[] { 1, 2, 3 };
List<Integer> list = Arrays.asList(numbers);

This way, you’ll have a List containing the elements 1, 2, and 3.

In Java 8, you can utilize streams to convert an array of primitive integers to a List of Integers:

int[] numbers = new int[] { 1, 2, 3 };
List<Integer> list = Arrays.stream(numbers)
                           .boxed()
                           .collect(Collectors.toList());

This code snippet uses Arrays.stream(numbers) to create a stream of integers, boxed() to convert each primitive int to an Integer object, and collect(Collectors.toList()) to collect the elements into a List.

Yes, you’re correct. The Arrays.stream() method doesn’t directly support boolean arrays (boolean[]). However, you can easily convert a boolean[] to a Boolean[] and then use streams:

boolean[] flags = new boolean[] { true, false, true };
Boolean[] objects = Arrays.stream(flags)
                          .boxed()
                          .toArray(Boolean[]::new);
List<Boolean> list = Arrays.asList(objects);

In this example, we first use Arrays.stream(flags) to get a Stream<Boolean> by boxing each boolean value. Then, we convert the stream to an array of Boolean objects using .toArray(Boolean[]::new). Finally, we create a List<Boolean> from the Boolean[] array using Arrays.asList(objects).