Arrays.asList return type mismatch confusion [duplicate] - java

This question already has answers here:
Boxing with Arrays.asList()
(2 answers)
Closed 9 years ago.
Why does the following not return a list of integers?
int[] ints = new int[] { 1, 2, 3, 4, 5 };
List<Integer> intsList = Arrays.asList(ints); //compilation error
But instead a List of int[]
While this
String[] strings = new String[] { "Hello", "World" };
List<String> stringsList = Arrays.asList(strings);
Returns a list of String. I am guessing it fails due to it being an array of primitives but why? And how do I actually return a list of int.

It's because Arrays.asList(new int[] { 1, 2, 3, 4, 5 }) will create a List<int[]> with one item, not a List<Integer> with five items.
Note however that this would do what you expected:
List<Integer> intsList = Arrays.asList(1, 2, 3, 4, 5);
Your other alternatives are:
to create an Integer[] in the first place, or
to populate your list in a loop

The method is defined as:
public static <T> List<T> asList(T... a)
So in your first case, T is int[] and you are passing a single object to the method (i.e. the array), therefore it returns a list of int[].
I think you are mistaking with asList(1, 2, 3, 4, 5) (i.e. 5 items)

The T in List<T> must be some subtype of java.lang.Object, which int is not. THe only other interpretation is, as we are using ... that you are supplying an array of int[], i.e. an int[][]. So you get List<int[]>.
String is a subtype of Object, so this works as expected. Also the only way it can work prior to varargs introduction in J2SE 5.0. Generally the interpretation of existing code should not alter between language versions.
Now, if you wanted a List<Integer> you could go through and box each integer. If there a lot of these elements in your program then memory may be an issue. You may want to use a third-party library that compactly backs a List<Integer> with an int[], or just stick with arrays for primitives. It's unfortunate that Java does not support value types.

Related

java Failed to convert int array to Set using Collectors.toSet() [duplicate]

This question already has answers here:
Java stream - map and store array of int into Set
(3 answers)
How do I convert a Java 8 IntStream to a List?
(5 answers)
Arrays.asList() not working as it should?
(12 answers)
Closed 2 days ago.
i can't understand basic thing here i have :
int[] arr = {2,5,2,4,6,6,1,5,4};
Set<Integer> orederSet = new HashSet<Integer>(Arrays.stream(arr).collect(Collectors.toSet()));
side note :
also this not working :
Set<Integer> orederSet = new HashSet<Integer>(Arrays.asList(arr));
which gives me compile error :
java: method collect in interface java.util.stream.IntStream cannot be applied to given types;
required: java.util.function.Supplier<R>,java.util.function.ObjIntConsumer<R>,java.util.function.BiConsumer<R,R>
found: java.util.stream.Collector<java.lang.Object,capture#1 of ?,java.util.Set<java.lang.Object>>
reason: cannot infer type-variable(s) R
(actual and formal argument lists differ in length)
I dont understand what is wrong in my code ..
Your arr is an int[]. That means you're calling Arrays#stream(int[]), which returns an IntStream. But none of the primitive stream interfaces1 have a #collect(Collector) method. You have to convert the IntStream into a Stream<Integer>. The easiest way to do that is with the IntStream#boxed() method.
int[] arr = {2, 5, 2, 4, 6, 6, 1, 5, 4};
Set<Integer> set =
Arrays.stream(arr) // IntStream
.boxed() // Stream<Integer>
.collect(Collectors.toSet()); // Set<Integer>
As for why the following doesn't work:
Set<Integer> set = new HashSet<>(Arrays.asList(arr));
That's due to Arrays.asList(arr) returning a List<int[]> rather than a List<Integer>.
Neither primitives nor arrays work especially well with generics. Arrays of primitives are worse. A primitive can at least be auto-boxed to the reference type (and vice versa, i.e., unboxed) when appropriate. But primitive arrays have no such special treatment.
1. The primitive stream interfaces include IntStream, LongStream, and DoubleStream.
Try to convert IntStream:
Set<Integer> orderSet = Arrays.stream(arr).boxed().collect(Collectors.toSet());

Problem when working with arrays in Java - code does not go inside the "if" statement [duplicate]

How do I convert an array to a list in Java?
I used the Arrays.asList() but the behavior (and signature) somehow changed from Java SE 1.4.2 (docs now in archive) to 8 and most snippets I found on the web use the 1.4.2 behaviour.
For example:
int[] numbers = new int[] { 1, 2, 3 };
Arrays.asList(numbers)
on 1.4.2 returns a list containing the elements 1, 2, 3
on 1.5.0+ returns a list containing the array 'numbers'
In many cases it should be easy to detect, but sometimes it can slip unnoticed:
Assert.assertTrue(Arrays.asList(numbers).indexOf(4) == -1);
In your example, it is because you can't have a List of a primitive type. In other words, List<int> is not possible.
You can, however, have a List<Integer> using the Integer class that wraps the int primitive. Convert your array to a List with the Arrays.asList utility method.
Integer[] numbers = new Integer[] { 1, 2, 3 };
List<Integer> list = Arrays.asList(numbers);
See this code run live at IdeOne.com.
In Java 8, you can use streams:
int[] numbers = new int[] { 1, 2, 3 };
Arrays.stream(numbers)
.boxed()
.collect(Collectors.toList());
We cannot have List<int> as int is a primitive type so we can only have List<Integer>.
Java 16
Java 16 introduces a new method on Stream API called toList(). This handy method returns an unmodifiable List containing the stream elements. So, trying to add a new element to the list will simply lead to UnsupportedOperationException.
int[] ints = new int[] {1,2,3,4,5};
Arrays.stream(ints).boxed().toList();
Java 8 (int array)
int[] ints = new int[] {1,2,3,4,5};
List<Integer> list11 =Arrays.stream(ints).boxed().collect(Collectors.toList());
Java 8 and below (Integer array)
Integer[] integers = new Integer[] {1,2,3,4,5};
List<Integer> list21 = Arrays.asList(integers); // returns a fixed-size list backed by the specified array.
List<Integer> list22 = new ArrayList<>(Arrays.asList(integers)); // good
List<Integer> list23 = Arrays.stream(integers).collect(Collectors.toList()); //Java 8 only
Need ArrayList and not List?
In case we want a specific implementation of List e.g. ArrayList then we can use toCollection as:
ArrayList<Integer> list24 = Arrays.stream(integers)
.collect(Collectors.toCollection(ArrayList::new));
Why list21 cannot be structurally modified?
When we use Arrays.asList the size of the returned list is fixed because the list returned is not java.util.ArrayList, but a private static class defined inside java.util.Arrays. So if we add or remove elements from the returned list, an UnsupportedOperationException will be thrown. So we should go with list22 when we want to modify the list. If we have Java8 then we can also go with list23.
To be clear list21 can be modified in sense that we can call list21.set(index,element) but this list may not be structurally modified i.e. cannot add or remove elements from the list. You can also check this answer of mine for more explanation.
If we want an immutable list then we can wrap it as:
List<Integer> list22 = Collections.unmodifiableList(Arrays.asList(integers));
Another point to note is that the method Collections.unmodifiableList returns an unmodifiable view of the specified list. An unmodifiable view collection is a collection that is unmodifiable and is also a view onto a backing collection. Note that changes to the backing collection might still be possible, and if they occur, they are visible through the unmodifiable view.
We can have a truly immutable list in Java 9 and 10.
Truly Immutable list
Java 9:
String[] objects = {"Apple", "Ball", "Cat"};
List<String> objectList = List.of(objects);
Java 10 (Truly Immutable list):
We can use List.of introduced in Java 9. Also other ways:
List.copyOf(Arrays.asList(integers))
Arrays.stream(integers).collect(Collectors.toUnmodifiableList());
Speaking about conversion way, it depends on why do you need your List.
If you need it just to read data. OK, here you go:
Integer[] values = { 1, 3, 7 };
List<Integer> list = Arrays.asList(values);
But then if you do something like this:
list.add(1);
you get java.lang.UnsupportedOperationException.
So for some cases you even need this:
Integer[] values = { 1, 3, 7 };
List<Integer> list = new ArrayList<Integer>(Arrays.asList(values));
First approach actually does not convert array but 'represents' it like a List. But array is under the hood with all its properties like fixed number of elements. Please note you need to specify type when constructing ArrayList.
The problem is that varargs got introduced in Java 5 and unfortunately, Arrays.asList() got overloaded with a vararg version too. So Arrays.asList(numbers) is understood by the Java 5 compiler as a vararg parameter of int arrays.
This problem is explained in more details in Effective Java 2nd Ed., Chapter 7, Item 42.
I recently had to convert an array to a List. Later on the program filtered the list attempting to remove the data. When you use the Arrays.asList(array) function, you create a fixed size collection: you can neither add nor delete. This entry explains the problem better than I can: Why do I get an UnsupportedOperationException when trying to remove an element from a List?.
In the end, I had to do a "manual" conversion:
List<ListItem> items = new ArrayList<ListItem>();
for (ListItem item: itemsArray) {
items.add(item);
}
I suppose I could have added conversion from an array to a list using an List.addAll(items) operation.
Even shorter:
List<Integer> list = Arrays.asList(1, 2, 3, 4);
Using Arrays
This is the simplest way to convert an array to List. However, if you try to add a new element or remove an existing element from the list, an UnsupportedOperationException will be thrown.
Integer[] existingArray = {1, 2, 3};
List<Integer> list1 = Arrays.asList(existingArray);
List<Integer> list2 = Arrays.asList(1, 2, 3);
// WARNING:
list2.add(1); // Unsupported operation!
list2.remove(1); // Unsupported operation!
Using ArrayList or Other List Implementations
You can use a for loop to add all the elements of the array into a List implementation, e.g. ArrayList:
List<Integer> list = new ArrayList<>();
for (int i : new int[]{1, 2, 3}) {
list.add(i);
}
Using Stream API in Java 8
You can turn the array into a stream, then collect the stream using different collectors: The default collector in Java 8 use ArrayList behind the screen, but you can also impose your preferred implementation.
List<Integer> list1, list2, list3;
list1 = Stream.of(1, 2, 3).collect(Collectors.toList());
list2 = Stream.of(1, 2, 3).collect(Collectors.toCollection(ArrayList::new));
list3 = Stream.of(1, 2, 3).collect(Collectors.toCollection(LinkedList::new));
See also:
Why do we use autoboxing and unboxing in Java?
When to use LinkedList over ArrayList?
Another workaround if you use Apache commons-lang:
int[] numbers = new int[] { 1, 2, 3 };
Arrays.asList(ArrayUtils.toObject(numbers));
Where ArrayUtils.toObject converts int[] to Integer[]
In Java 9 you have the even more elegant solution of using immutable lists via the new convenience factory method List.of:
List<String> immutableList = List.of("one","two","three");
(shamelessly copied from here )
One-liner:
List<Integer> list = Arrays.asList(new Integer[] {1, 2, 3, 4});
If you are targeting Java 8 (or later), you can try this:
int[] numbers = new int[] {1, 2, 3, 4};
List<Integer> integers = Arrays.stream(numbers)
.boxed().collect(Collectors.<Integer>toList());
NOTE:
Pay attention to the Collectors.<Integer>toList(), this generic method helps you to avoid the error "Type mismatch: cannot convert from List<Object> to List<Integer>".
you have to cast in to array
Arrays.asList((Object[]) array)
Using Guava:
Integer[] array = { 1, 2, 3};
List<Integer> list = Lists.newArrayList(sourceArray);
Using Apache Commons Collections:
Integer[] array = { 1, 2, 3};
List<Integer> list = new ArrayList<>(6);
CollectionUtils.addAll(list, array);
I've had the same problem and wrote a generic function that takes an array and returns an ArrayList of the same type with the same contents:
public static <T> ArrayList<T> ArrayToArrayList(T[] array) {
ArrayList<T> list = new ArrayList<T>();
for(T elmt : array) list.add(elmt);
return list;
}
Given Array:
int[] givenArray = {2,2,3,3,4,5};
Converting integer array to Integer List
One way: boxed() -> returns the IntStream
List<Integer> givenIntArray1 = Arrays.stream(givenArray)
.boxed()
.collect(Collectors.toList());
Second Way: map each element of the stream to Integer and then collect
NOTE:
Using mapToObj you can covert each int element into string stream, char stream etc by casing i to (char)i
List<Integer> givenIntArray2 = Arrays.stream(givenArray)
.mapToObj(i->i)
.collect(Collectors.toList());
Converting One array Type to Another Type Example:
List<Character> givenIntArray2 = Arrays.stream(givenArray)
.mapToObj(i->(char)i)
.collect(Collectors.toList());
So it depends on which Java version you are trying-
Java 7
Arrays.asList(1, 2, 3);
OR
final String arr[] = new String[] { "G", "E", "E", "K" };
final List<String> initialList = new ArrayList<String>() {{
add("C");
add("O");
add("D");
add("I");
add("N");
}};
// Elements of the array are appended at the end
Collections.addAll(initialList, arr);
OR
Integer[] arr = new Integer[] { 1, 2, 3 };
Arrays.asList(arr);
In Java 8
int[] num = new int[] {1, 2, 3};
List<Integer> list = Arrays.stream(num)
.boxed().collect(Collectors.<Integer>toList())
Reference - http://www.codingeek.com/java/how-to-convert-array-to-list-in-java/
Can you improve this answer please as this is what I use but im not 100% clear. It works fine but intelliJ added new WeatherStation[0]. Why the 0 ?
public WeatherStation[] removeElementAtIndex(WeatherStation[] array, int index)
{
List<WeatherStation> list = new ArrayList<WeatherStation>(Arrays.asList(array));
list.remove(index);
return list.toArray(new WeatherStation[0]);
}
Use this to convert an Array arr to List.
Arrays.stream(arr).collect(Collectors.toList());
An example of defining a generic method to convert an array to a list:
public <T> List<T> fromArrayToList(T[] a) {
return Arrays.stream(a).collect(Collectors.toList());
}
use two line of code to convert array to list if you use it in integer value
you must use autoboxing type for primitive data type
Integer [] arr={1,2};
List<Integer> listInt=Arrays.asList(arr);
As of Java 8, the following should do
int[] temp = {1, 2, 3, 4, 5};
List<Integer> tempList = Arrays.stream(temp).boxed().collect(Collectors.toList());
If you are trying to optimize for memory, etc., (and don't want to pull in external libraries) it's simpler than you think to implement your own immutable "array view list" – you just need to extend java.util.AbstractList.
class IntArrayViewList extends AbstractList<Integer> {
int[] backingArray;
int size;
IntArrayViewList(int[] backingArray, int size) {
this.backingArray = backingArray;
this.size = size;
}
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
int i = 0;
#Override
public boolean hasNext() {
return i < size;
}
#Override
public Integer next() {
return get(i++);
}
};
}
public int size() {
return size;
}
public Integer get(int i) {
return backingArray[i];
}
}
int is a primitive. Primitives can’t accept null and have default value. Hence, to accept null you need to use wrapper class Integer.
Option 1:
int[] nos = { 1, 2, 3, 4, 5 };
Integer[] nosWrapped = Arrays.stream(nos).boxed()   
.toArray(Integer[]::new);
nosWrapped[5] = null // can store null
Option 2:
You can use any data structure that uses the wrapper class Integer
int[] nos = { 1, 2, 3, 4, 5 };
List<Integer> = Arrays.asList(nos)
I started looking at this by trying to reduce the amount of code preparing the input of some test cases. I see a lot of effort around trying to include advanced and new features along with Arrays.asList(), but below the code chosen due simplicity:
//Integer input[]
List<Integer> numbers = Arrays.asList(new Integer[]{1, 2 ,3, 4, 5, 4, 3, 2, 1, 3, 4});
//String input[]
List<String> names = Arrays.asList(new String[]{"Jhon", "Lucas", "Daniel", "Jim", "Sam"});
//String input[]
List<Character> letters = Arrays.asList(new Character[]{'A', 'B', 'K', 'J', 'F'});
Please notice that Anonymous array example will work just with Arrays of Non Primitive Types as the API uses Generics, that's the reason you can see several 2 line examples around, more info here: Why don't Java Generics support primitive types?
For newer JDKs there is another simpler option, the below examples are equivalent to the ones show above:
//Integer
List<Integer> numbers = Arrays.asList(1, 2 ,3, 4, 5, 4, 3, 2, 1, 3, 4);
//String
List<String> names = Arrays.asList("Jhon", "Lucas", "Daniel", "Jim", "Sam");
//Character
List<Character> letters = Arrays.asList('A', 'B', 'K', 'J', 'F');

java : Understanding Arrays.asList(T...array) method for primitive types

I wrote following code and was surprised to see the output:
Integer a = 211;
int b = 211;
int[] array = {210,211,212};
System.out.println(Arrays.asList(array).contains(a));
System.out.println(Arrays.asList(array).contains(b));
Output:
false
false
I found this question and some other questions linked to it and learned that asList method doesn't Autobox stuffs. I checked the returned type in eclipse javadoc preview:
I couldn't quite understand this return type. int[] is an object and not a primitive so its fine. I'm sure that I'm not getting List<Integer> (something which I expected) but I'm not sure how to use the thing which is being returned. My questions are:
1. How exactly do I expect that list methods will work when I'm expecting an List of Integer and getting a List of int[] ?
2. In case of Strings the return type is List of String and not List of String[]. What sort of implementation differences are there?
3. What good is this method for primitives if things are so uncertain?
There are obviously 3 questions here so lets tackle them one by one:
How exactly do I expect that list methods will work when I'm expecting an List of Integer and getting a List of int[] ?
Well, List methods will work exactly as expected, a List<T> is a list of types T. Here T is an int[] so a List<int[]> will contains arrays as each element:
[{1, 2}, {3, 4}, {1, 6}]
So get(i) will return the ith element. In the case of Arrays.asList the List contains a single element, namely the int[] so:
int[] array = {210,211,212};
List<int[]> list = Arrays.asList(array);
Will be
[{210, 211, 212}]
And so
list.get(0)[0] == 210
In case of Strings the return type is List of String and not List of String[]. What sort of implementation differences are there?
String is an Object, not a primitive type. The difference follows from that.
What good is this method for primitives if things are so uncertain?
Things are not uncertain. This method results in defined and predictable behaviour. It's just not very useful for primitives. This is (yet another) side effect of combining Java's type system with generics.
Note with Java 8 the conversion of an int[] to a List<Integer> is very simple:
List<Integer> list = Arrays.stream(array).
boxed().
collect(toList());
You are not getting a Lit or a List (which can't be), you're getting a List of arrays of integer.
So your list does not contain 211, it contains an array that then contains 211.
The array is not "unrolled" into the list, it is added "as is" to a newly created list.
So :
System.out.println(Arrays.asList(array).contains(array)); // Will return true
System.out.println(Arrays.asList(a).contains(a)); // Will return true
It is because Arrays.asList() is a variadic generic function. Change this,
int[] array = {210,211,212};
to
Integer[] array = { 210, 211, 212 };
And the output will be true and true.
Arrays.asList takes objects as params. Since int[] is an object, you get the List.
If you want a list of integers you should do Arrays.asList(211,212,213).
int[] array = {210,211,212};
Arrays.asList(array)
is equal to
List<int[]> asList = Arrays.asList(array);
Change
int[] array = {210,211,212}; to Integer[] array = {210,211,212}; and it will work.
and its equals to List<Integer> asList = Arrays.asList(array);

Trying to convert array of ints to a list

I'm trying to convert an array of type int to a List by doing
List<Integer> endingRoutesBusStopsList = Arrays.asList(endingRoutesBusStops);
but for some reason I keep getting an error saying
Type mismatch: cannot convert from List<int[]> to List<Integer>
I don't understand what the issue is.
I know doing
List<int[]> endingRoutesBusStopsList = Arrays.asList(endingRoutesBusStops);
will solve the error, but then I can't use it the way I want.
Anyone have any ideas?
This is caused by the fact that int[] is different from Integer[]. Autoboxing does not work on Arrays.
The issue is because an "int[]" is an Object,
Arrays.asList(T...) gets generic vararg, that it means it treats "int[]" as "Object" (the common superclass for array int[] and Integer is Object)
so that from asList method perspective you don't pass an array of ints, but you pass an object .
In any way you should make implicit convertion from int to wrapper Integer. It is advisable to make it explicitly.
We are missing some more of your code, but in general, let me try and answer with code:
This works:
Integer[] arrayOfInt = { Integer.valueOf(0), Integer.valueOf(1) };
List<Integer> listOfInt = Arrays.asList(arrayOfInt);
This works too because the primitive "1" is autoboxed to an Integer object:
Integer[] arrayOfInt = { 1, 2, 3, 4 };
List<Integer> listOfInt = Arrays.asList(arrayOfInt);
Finally, this won't work because an int[] cannot be autoboxed to Integer[]:
int[] arrayOfInt = { 1, 2, 3, 4 };
List<Integer> listOfInt = Arrays.asList(arrayOfInt);
UPDATE: this comes from way down in the comments in a discussion with #MichaelBorek . This example repeatedly tries the same code either autoboxing or not. The cost of autoboxing seems to be that the code that uses it takes 5 times longer than the one that uses Objects directly.

Converting array to list in Java

How do I convert an array to a list in Java?
I used the Arrays.asList() but the behavior (and signature) somehow changed from Java SE 1.4.2 (docs now in archive) to 8 and most snippets I found on the web use the 1.4.2 behaviour.
For example:
int[] numbers = new int[] { 1, 2, 3 };
Arrays.asList(numbers)
on 1.4.2 returns a list containing the elements 1, 2, 3
on 1.5.0+ returns a list containing the array 'numbers'
In many cases it should be easy to detect, but sometimes it can slip unnoticed:
Assert.assertTrue(Arrays.asList(numbers).indexOf(4) == -1);
In your example, it is because you can't have a List of a primitive type. In other words, List<int> is not possible.
You can, however, have a List<Integer> using the Integer class that wraps the int primitive. Convert your array to a List with the Arrays.asList utility method.
Integer[] numbers = new Integer[] { 1, 2, 3 };
List<Integer> list = Arrays.asList(numbers);
See this code run live at IdeOne.com.
In Java 8, you can use streams:
int[] numbers = new int[] { 1, 2, 3 };
Arrays.stream(numbers)
.boxed()
.collect(Collectors.toList());
We cannot have List<int> as int is a primitive type so we can only have List<Integer>.
Java 16
Java 16 introduces a new method on Stream API called toList(). This handy method returns an unmodifiable List containing the stream elements. So, trying to add a new element to the list will simply lead to UnsupportedOperationException.
int[] ints = new int[] {1,2,3,4,5};
Arrays.stream(ints).boxed().toList();
Java 8 (int array)
int[] ints = new int[] {1,2,3,4,5};
List<Integer> list11 =Arrays.stream(ints).boxed().collect(Collectors.toList());
Java 8 and below (Integer array)
Integer[] integers = new Integer[] {1,2,3,4,5};
List<Integer> list21 = Arrays.asList(integers); // returns a fixed-size list backed by the specified array.
List<Integer> list22 = new ArrayList<>(Arrays.asList(integers)); // good
List<Integer> list23 = Arrays.stream(integers).collect(Collectors.toList()); //Java 8 only
Need ArrayList and not List?
In case we want a specific implementation of List e.g. ArrayList then we can use toCollection as:
ArrayList<Integer> list24 = Arrays.stream(integers)
.collect(Collectors.toCollection(ArrayList::new));
Why list21 cannot be structurally modified?
When we use Arrays.asList the size of the returned list is fixed because the list returned is not java.util.ArrayList, but a private static class defined inside java.util.Arrays. So if we add or remove elements from the returned list, an UnsupportedOperationException will be thrown. So we should go with list22 when we want to modify the list. If we have Java8 then we can also go with list23.
To be clear list21 can be modified in sense that we can call list21.set(index,element) but this list may not be structurally modified i.e. cannot add or remove elements from the list. You can also check this answer of mine for more explanation.
If we want an immutable list then we can wrap it as:
List<Integer> list22 = Collections.unmodifiableList(Arrays.asList(integers));
Another point to note is that the method Collections.unmodifiableList returns an unmodifiable view of the specified list. An unmodifiable view collection is a collection that is unmodifiable and is also a view onto a backing collection. Note that changes to the backing collection might still be possible, and if they occur, they are visible through the unmodifiable view.
We can have a truly immutable list in Java 9 and 10.
Truly Immutable list
Java 9:
String[] objects = {"Apple", "Ball", "Cat"};
List<String> objectList = List.of(objects);
Java 10 (Truly Immutable list):
We can use List.of introduced in Java 9. Also other ways:
List.copyOf(Arrays.asList(integers))
Arrays.stream(integers).collect(Collectors.toUnmodifiableList());
Speaking about conversion way, it depends on why do you need your List.
If you need it just to read data. OK, here you go:
Integer[] values = { 1, 3, 7 };
List<Integer> list = Arrays.asList(values);
But then if you do something like this:
list.add(1);
you get java.lang.UnsupportedOperationException.
So for some cases you even need this:
Integer[] values = { 1, 3, 7 };
List<Integer> list = new ArrayList<Integer>(Arrays.asList(values));
First approach actually does not convert array but 'represents' it like a List. But array is under the hood with all its properties like fixed number of elements. Please note you need to specify type when constructing ArrayList.
The problem is that varargs got introduced in Java 5 and unfortunately, Arrays.asList() got overloaded with a vararg version too. So Arrays.asList(numbers) is understood by the Java 5 compiler as a vararg parameter of int arrays.
This problem is explained in more details in Effective Java 2nd Ed., Chapter 7, Item 42.
I recently had to convert an array to a List. Later on the program filtered the list attempting to remove the data. When you use the Arrays.asList(array) function, you create a fixed size collection: you can neither add nor delete. This entry explains the problem better than I can: Why do I get an UnsupportedOperationException when trying to remove an element from a List?.
In the end, I had to do a "manual" conversion:
List<ListItem> items = new ArrayList<ListItem>();
for (ListItem item: itemsArray) {
items.add(item);
}
I suppose I could have added conversion from an array to a list using an List.addAll(items) operation.
Even shorter:
List<Integer> list = Arrays.asList(1, 2, 3, 4);
Using Arrays
This is the simplest way to convert an array to List. However, if you try to add a new element or remove an existing element from the list, an UnsupportedOperationException will be thrown.
Integer[] existingArray = {1, 2, 3};
List<Integer> list1 = Arrays.asList(existingArray);
List<Integer> list2 = Arrays.asList(1, 2, 3);
// WARNING:
list2.add(1); // Unsupported operation!
list2.remove(1); // Unsupported operation!
Using ArrayList or Other List Implementations
You can use a for loop to add all the elements of the array into a List implementation, e.g. ArrayList:
List<Integer> list = new ArrayList<>();
for (int i : new int[]{1, 2, 3}) {
list.add(i);
}
Using Stream API in Java 8
You can turn the array into a stream, then collect the stream using different collectors: The default collector in Java 8 use ArrayList behind the screen, but you can also impose your preferred implementation.
List<Integer> list1, list2, list3;
list1 = Stream.of(1, 2, 3).collect(Collectors.toList());
list2 = Stream.of(1, 2, 3).collect(Collectors.toCollection(ArrayList::new));
list3 = Stream.of(1, 2, 3).collect(Collectors.toCollection(LinkedList::new));
See also:
Why do we use autoboxing and unboxing in Java?
When to use LinkedList over ArrayList?
Another workaround if you use Apache commons-lang:
int[] numbers = new int[] { 1, 2, 3 };
Arrays.asList(ArrayUtils.toObject(numbers));
Where ArrayUtils.toObject converts int[] to Integer[]
In Java 9 you have the even more elegant solution of using immutable lists via the new convenience factory method List.of:
List<String> immutableList = List.of("one","two","three");
(shamelessly copied from here )
One-liner:
List<Integer> list = Arrays.asList(new Integer[] {1, 2, 3, 4});
If you are targeting Java 8 (or later), you can try this:
int[] numbers = new int[] {1, 2, 3, 4};
List<Integer> integers = Arrays.stream(numbers)
.boxed().collect(Collectors.<Integer>toList());
NOTE:
Pay attention to the Collectors.<Integer>toList(), this generic method helps you to avoid the error "Type mismatch: cannot convert from List<Object> to List<Integer>".
you have to cast in to array
Arrays.asList((Object[]) array)
Using Guava:
Integer[] array = { 1, 2, 3};
List<Integer> list = Lists.newArrayList(sourceArray);
Using Apache Commons Collections:
Integer[] array = { 1, 2, 3};
List<Integer> list = new ArrayList<>(6);
CollectionUtils.addAll(list, array);
I've had the same problem and wrote a generic function that takes an array and returns an ArrayList of the same type with the same contents:
public static <T> ArrayList<T> ArrayToArrayList(T[] array) {
ArrayList<T> list = new ArrayList<T>();
for(T elmt : array) list.add(elmt);
return list;
}
Given Array:
int[] givenArray = {2,2,3,3,4,5};
Converting integer array to Integer List
One way: boxed() -> returns the IntStream
List<Integer> givenIntArray1 = Arrays.stream(givenArray)
.boxed()
.collect(Collectors.toList());
Second Way: map each element of the stream to Integer and then collect
NOTE:
Using mapToObj you can covert each int element into string stream, char stream etc by casing i to (char)i
List<Integer> givenIntArray2 = Arrays.stream(givenArray)
.mapToObj(i->i)
.collect(Collectors.toList());
Converting One array Type to Another Type Example:
List<Character> givenIntArray2 = Arrays.stream(givenArray)
.mapToObj(i->(char)i)
.collect(Collectors.toList());
So it depends on which Java version you are trying-
Java 7
Arrays.asList(1, 2, 3);
OR
final String arr[] = new String[] { "G", "E", "E", "K" };
final List<String> initialList = new ArrayList<String>() {{
add("C");
add("O");
add("D");
add("I");
add("N");
}};
// Elements of the array are appended at the end
Collections.addAll(initialList, arr);
OR
Integer[] arr = new Integer[] { 1, 2, 3 };
Arrays.asList(arr);
In Java 8
int[] num = new int[] {1, 2, 3};
List<Integer> list = Arrays.stream(num)
.boxed().collect(Collectors.<Integer>toList())
Reference - http://www.codingeek.com/java/how-to-convert-array-to-list-in-java/
Can you improve this answer please as this is what I use but im not 100% clear. It works fine but intelliJ added new WeatherStation[0]. Why the 0 ?
public WeatherStation[] removeElementAtIndex(WeatherStation[] array, int index)
{
List<WeatherStation> list = new ArrayList<WeatherStation>(Arrays.asList(array));
list.remove(index);
return list.toArray(new WeatherStation[0]);
}
Use this to convert an Array arr to List.
Arrays.stream(arr).collect(Collectors.toList());
An example of defining a generic method to convert an array to a list:
public <T> List<T> fromArrayToList(T[] a) {
return Arrays.stream(a).collect(Collectors.toList());
}
use two line of code to convert array to list if you use it in integer value
you must use autoboxing type for primitive data type
Integer [] arr={1,2};
List<Integer> listInt=Arrays.asList(arr);
As of Java 8, the following should do
int[] temp = {1, 2, 3, 4, 5};
List<Integer> tempList = Arrays.stream(temp).boxed().collect(Collectors.toList());
If you are trying to optimize for memory, etc., (and don't want to pull in external libraries) it's simpler than you think to implement your own immutable "array view list" – you just need to extend java.util.AbstractList.
class IntArrayViewList extends AbstractList<Integer> {
int[] backingArray;
int size;
IntArrayViewList(int[] backingArray, int size) {
this.backingArray = backingArray;
this.size = size;
}
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
int i = 0;
#Override
public boolean hasNext() {
return i < size;
}
#Override
public Integer next() {
return get(i++);
}
};
}
public int size() {
return size;
}
public Integer get(int i) {
return backingArray[i];
}
}
int is a primitive. Primitives can’t accept null and have default value. Hence, to accept null you need to use wrapper class Integer.
Option 1:
int[] nos = { 1, 2, 3, 4, 5 };
Integer[] nosWrapped = Arrays.stream(nos).boxed()   
.toArray(Integer[]::new);
nosWrapped[5] = null // can store null
Option 2:
You can use any data structure that uses the wrapper class Integer
int[] nos = { 1, 2, 3, 4, 5 };
List<Integer> = Arrays.asList(nos)
I started looking at this by trying to reduce the amount of code preparing the input of some test cases. I see a lot of effort around trying to include advanced and new features along with Arrays.asList(), but below the code chosen due simplicity:
//Integer input[]
List<Integer> numbers = Arrays.asList(new Integer[]{1, 2 ,3, 4, 5, 4, 3, 2, 1, 3, 4});
//String input[]
List<String> names = Arrays.asList(new String[]{"Jhon", "Lucas", "Daniel", "Jim", "Sam"});
//String input[]
List<Character> letters = Arrays.asList(new Character[]{'A', 'B', 'K', 'J', 'F'});
Please notice that Anonymous array example will work just with Arrays of Non Primitive Types as the API uses Generics, that's the reason you can see several 2 line examples around, more info here: Why don't Java Generics support primitive types?
For newer JDKs there is another simpler option, the below examples are equivalent to the ones show above:
//Integer
List<Integer> numbers = Arrays.asList(1, 2 ,3, 4, 5, 4, 3, 2, 1, 3, 4);
//String
List<String> names = Arrays.asList("Jhon", "Lucas", "Daniel", "Jim", "Sam");
//Character
List<Character> letters = Arrays.asList('A', 'B', 'K', 'J', 'F');

Categories

Resources