adding an ArrayList to ArrayList - java

Conceptually what is going on here?
I have an ArrayList
ArrayList<SomeClass> myArray = new ArrayList<SomeClass>();
then I add something to it like this
myArray.add(new myArray(1, 2, 3));

I have an array
ArrayList myArray = new ArrayList();
No, you don't have an array. Arrays are declared using brackes [], like this:
int[] myArray;
You have an object of ArrayList class. This object will use an array internally to store the data and dynamically change the array for a newer one when needs to assign more values.
then I add something to it like this
myArray.add(new myArray(1, 2, 3));
Conceptually, this is wrong and won't even compile. If you want to add more than one value in your array, you should use ArrayList#addAll method, that receives another collection. Then, you have two ways to pass a Collection in one statement:
Create a list using Arrays#asList:
myArray.addAll(Arrays.asList(1, 2, 3));
You can use double brace initialization:
myArray.addAll(new ArrayList() {{
add(1);
add(2);
add(3);
}});
You should take into account that you should specify the generic for your ArrayList instead of using raw data:
ArrayList<Integer> myArray = new ArrayList<Integer>();
myArray.addAll(new ArrayList<Integer>() {{
add(1);
add(2);
add(3);
}});
More info:
Java Tutorial. Collections
Initialization of an ArrayList in one line
Note that if you have an ArrayList that is tied to a custom class, let's say ArrayList<SomeClass> myArrayList, then the compiler prevents you to add elements to the list that doesn't pass the IS-A test (noted by instanceof operator), so this code:
ArrayList<SomeClass> myArrayList = new ArrayList<SomeClass>();
myArrayList..addAll(new ArrayList<Integer>() {{
add(1);
add(2);
add(3);
}});
Won't be able to compile since Integer is not a SomeClass. Similar with this piece of code:
ArrayList<SomeClass> myArrayList = new ArrayList<SomeClass>();
myArray.add(Arrays.asList(1, 2, 3));
But due to type erasure you can trick the compiler by using raw types. For example:
public void addData(ArrayList yourArrayList, Object anyData) {
yourArrayList.add(anyData);
}
Then in your code, you call this method:
ArrayList<String> myArrayList = new ArrayList<String>(); //allows Strings only
myArrayList.add("Hello world");
//myArrayList.add(0); //this won't compile because trying to add an Integer
addData(myArrayList, 0); //this will compile for using raw ArrayList and sending an Integer
System.out.println(myArrayList);
It will print:
[Hello world, 0]

myArray.add(new myArray(1, 2, 3));
This is not correct and don't compile, cause myArray is not a type, it's just a reference, you need something of type integer or if you want to add another list, then use addAll.
You could use something like this.
List<Integer> myArray = new ArrayList<>(); // specify with generics type parameter
//do some things and then
myArray.addAll(Arrays.asList(1,2,3)); // use this helper method to add a list to another list
Or if you want to only create and populate it, just use
List<Integer> myArray = Arrays.asList(1,2,3,4,5);

I think I know what you're trying to do, say you have this.
ArrayList<Integer[]> myArray = new ArrayList<Integer[]>();
and you wanted to add an array to it, you're basically going to call
myArray.add(((Integer[]) new int[] { 0, 1, 2 }));
Which will add the array [0, 1, 2] to the next index in the ArrayList.
For exmaple, the following code
ArrayList<Integer[]> myArray = new ArrayList<Integer[]>();
myArray.add(((Integer[]) new int[] { 0, 1, 2 }));
myArray.add(((Integer[]) new int[] { 1, 0, 2 }));
myArray.add(((Integer[]) new int[] { 3, 2, 1 }));
Would create the following results:
myArray index 0 = [0, 1, 2]
myArray index 1 = [1, 0, 2]
myArray index 2 = [3, 2, 1]
Is this your question?

You don't actually have an array, you have an ArrayList. An ArrayList is a resizable implementation of the List interface. This means, among other things, that you don't have to define a length like you would with an array.
I don't think the code you have provided will actually compile because when you go:
myArray.add(new myArray(1, 2, 3));
you haven't provided a type. You should go something like:
myArray.add(new ArrayList<Integer>(Arrays.asList(1,2,3)));
Using asList() will give almost the equivalent of assigning "default" values to an array. The array equivalent would look something like this:
Integer[] intArray = new Integer[] {1,2,3};
You should also parameterize your ArrayList(s), this basically means you are saying what that ArrayList can hold. For instance:
ArrayList<Integer>
Can hold Integers.
The reason you must use a wrapper class (Integer & not int) is because Collections in Java don't permit you to store primitive types such as int or double.
You can have a Collection holding another Collection. In this case you could go:
ArrayList<ArrayList<Integer>> myArrayList = new ArrayList<ArrayList<Integer>>();
myArrayList.add(new ArrayList<Integer>(Arrays.asList(1, 2, 3)));
myArrayList.add(new ArrayList<Integer>(Arrays.asList(9, 12, 24)));
for (ArrayList<Integer> index : myArrayList) {
System.out.println(index);
}
Here you have an ArrayList holding two other ArrayLists. This results in the printing of:
[1, 2, 3]
[9, 12, 24]

Related

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');

Add Item to the ArrayList of ArrayList

I have an ArrayList of ArrayList like the following code and I'm intended to add one item to an existed arraylist and save it as well as keeping the old arrayList.
ArrayList<ArrayList<Integer>> bigArr = new ArrayList<ArrayList<Integer>> ();
ArrayList<Integer> arr = new ArrayList<Integer> ();
arr.add(1);
arr.add(2);
arr.add(3);
bigArr.add(arr);
ArrayList<Integer> tt = bigArr.get(0);
tt.add(4);
bigArr.add(tt);
System.out.println(bigArr);
But the thing is that happens is that it prints [[1, 2, 3, 4], [1, 2, 3, 4]] instead of [[1, 2, 3], [1, 2, 3, 4]]. Can someone please tell me what should I do to get the second output?
Create two lists instead of reusing the first list.
ArrayList<ArrayList<Integer>> bigArr = new ArrayList<ArrayList<Integer>> ();
ArrayList<Integer> arr = new ArrayList<Integer> ();
arr.add(1);
arr.add(2);
arr.add(3);
bigArr.add(arr);
ArrayList<Integer> tt = new ArrayList<Integer>(arr); // Create a new list based on the elements of the given list
tt.add(4);
bigArr.add(tt);
System.out.println(bigArr);
Object type parameter's references are pass by value but the
memory location that is pointed by them remains same. So changing anything using any reference variable will affect the same
Object.
So here tt and arr is pointing to the same memory location means if you change something in one of them that gets reflected to other as well.
Because your tt is still pointing to the same arraylist object. It's modifying the same object.
Solution: Make a new list object by copying old list and add item in that list then add list to main list.
Lists are objects with mutable state. This means that adding or removing items will change the state of the List your variable is pointing to. You create a single arr = ArrayList<Integer>, to which you add the values 1, 2, 3. You then add this list to the bigArr list of lists. Now, the first element of bigArr and arr both point to the same physical object. The moment you retrieve it from bigArr and store it in the tt variable, you have three ways to access the same list.
What you want, is a new version (copy) of your initial list at bigArr.get(0) and add the new value to that list. The easiest way to do this is to use ArrayList's copy constructor when you retrieve it from the bigArr. This is already explained in the answer given by Smutje:
ArrayList<Integer> tt = new ArrayList<Integer> (arr);

integer array in a collection

I would like to have a collection that holds arrays of integers.
List<int[]> pairs = new ArrayList<>();
in order to add there an element I have to:
int[] newArray = {1, 2};
pairs.add(newArray);
Can someone explain my why the below does not work:
pairs.add({1,2});
is there any other way to add {1,2} to pairs without creating newArray object?
Most of the time, you'll need to do new int[] { 1, 2 }:
pairs.add( new int[] {1,2} );
The only place that you can avoid the new int[] is when you're declaring a variable of type int[], as you've done with int[] newArray = {1, 2};. It's just a limitation of the language design. In particular, you can read 10.6. Array Initializers in the specification, which states that:
An array initializer may be specified in a declaration (§8.3, §9.3,
§14.4), or as part of an array creation expression (§15.10), to create
an array and provide some initial values.
The important thing to take away from that is that { 1, 2 }, is an array initializer, and you can use it in a declaration (int[] newArray = {1, 2};), or in an array creation expression (new int[] { 1, 2 }); you can't use it on its own.
You got the syntax slightly wrong.
Try this: pairs.add(new int[]{1,2});

Add multiple items to an already initialized arraylist in Java

My arraylist might be populated differently based on a user setting, so I've initialized it with
ArrayList<Integer> arList = new ArrayList<Integer>();
How can I add hundreds of integers without doing it one by one with arList.add(55);?
If you have another list that contains all the items you would like to add you can do arList.addAll(otherList). Alternatively, if you will always add the same elements to the list you could create a new list that is initialized to contain all your values and use the addAll() method, with something like
Integer[] otherList = new Integer[] {1, 2, 3, 4, 5};
arList.addAll(Arrays.asList(otherList));
or, if you don't want to create that unnecessary array:
arList.addAll(Arrays.asList(1, 2, 3, 4, 5));
Otherwise you will have to have some sort of loop that adds the values to the list individually.
What is the "source" of those integers? If it is something that you need to hard code in your source code, you may do
arList.addAll(Arrays.asList(1,1,2,3,5,8,13,21));
Collections.addAll is a varargs method which allows us to add any number of items to a collection in a single statement:
List<Integer> list = new ArrayList<>();
Collections.addAll(list, 1, 2, 3, 4, 5);
It can also be used to add array elements to a collection:
Integer[] arr = ...;
Collections.addAll(list, arr);
If you are looking to avoid multiple code lines to save space, maybe this syntax could be useful:
java.util.ArrayList lisFieldNames = new ArrayList() {
{
add("value1");
add("value2");
}
};
Removing new lines, you can show it compressed as:
java.util.ArrayList lisFieldNames = new ArrayList() {
{
add("value1"); add("value2"); (...);
}
};
Java 9+ now allows this:
List<Integer> arList = List.of(1,2,3,4,5);
The list will be immutable though.
In a Kotlin way;
val arList = ArrayList<String>()
arList.addAll(listOf(1,2,3,4,5))
If you needed to add a lot of integers it'd probably be easiest to use a for loop. For example, adding 28 days to a daysInFebruary array.
ArrayList<Integer> daysInFebruary = new ArrayList<>();
for(int i = 1; i <= 28; i++) {
daysInFebruary.add(i);
}
I believe scaevity's answer is incorrect. The proper way to initialize with multiple values would be this...
int[] otherList = {1,2,3,4,5};
So the full answer with the proper initialization would look like this
int[] otherList = {1,2,3,4,5};
arList.addAll(Arrays.asList(otherList));

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