Different ways to make a list in Java
Tags: java, beginners, arrays, codenewbie
Published: 2021-03-28 14:37:16

Lists are really important. They add the flexibility to resize automatically when adding or removing an element. This is particularly handy when you're taking input from a user in some form, and you don't know how many objects you will need to store in some array. As arrays are of fixed size when they are initialised, if we wanted to resize them, we'd need to create a new bigger array and copy the elements over. This is perfectly possible, but the List type does this work for you.

So, we know why, lets see the many ways we can create a List.
##ArrayList<>()
The first list type that most of us will use though is the `ArrayList`. It keeps elements ordered in the sequence they were input. The simplest way to declare and initialise this type of List, with String elements, is like so;

```
List<String> list = new ArrayList<>();
list.add("Here");
list.add("we");
list.add("add");
list.add("elements");
```
This method of creating and adding elements is particularly useful if we are iterating over some other data structure or input, getting elements until the input stops. For example with the 
`Scanner` and standard input stream in your IDE;

```
Scanner scan = new Scanner(System.in);
// user input = 1 2 3 4 e
while(scan.hasNextInt()) { // returns true if element is an int
    list.add(scan.nextInt());
}
// list = {1,2,3,4}
```
##Arrays.asList()
That's a great way to get an unknown number of elements into our List, but what if we already have an array we need to convert into a List? There's a ~~app~~ utility method for that! From the `Arrays` class;
```
String[] strings = new String[]{"Here's", "some", "strings",
    "in a", "string array"};
List<String> asList = Arrays.asList(strings);
```

Voila, our `String[]` is now a List. We can add to it or remove elements as we please. Be aware though, that the array you enter as the argument for `Arrays.asList(array)`, is taken and used as the basis for the List (the list is *backed* by the array). Any changes to the original array will be reflected in the List. This is also true vice versa, if you alter the List it will be reflected in the array.
```
strings[1] = "altered the string array"; // change the element at 
                                         // index 1
System.out.println(asList); // [Here's, altered the string array, 
                            // strings, in a, string array]
```
So, just be careful with the source array otherwise you may get some unexpected results.
##List.of()
The next way to create a List quickly is `List.of()`. This is a static method from the `List` interface, static means we can call the method without an object instance, like;
```
Person personInstance = new Person();
int age = personInstance.getAge(); // instance method

double pi = Math.PI; // static field from the Math class

```
The drawback (or benefit) with `List.of()` is it returns an immutable list. This means you cannot add or remove elements. Something to keep in mind, and depending on your situation, this might fit your need. 
```
List<String> listOfList = List.of("Can't", "change", "this", 
    "list");
listOfList.add("add me please"); // throws 
                                 // UnsupportedOperationException
```
You should know though, that the internal state of an element can still be altered. That is, if you had a list of `Person()`s, you could call the statement -
```
listOf.get(1).setAge(32);
```
without any exception being thrown.
##Arrays.stream()
The last way I will propose to create your List is using streams. Streams were added to Java in version 8, in 2014. They are a big topic, and well worth looking into as they make working with data structures much easier once you get the hang of them. In essence, you send a group of objects in one end, and perform various operations on this group in the middle (intermediate operations), then collect them all up again at the end (terminal operation) and package them back into a data structure of your pleasing.
```
List<String> streamList = 
    Arrays.stream(strings).collect(Collectors.toList());
```
This seems overkill compared to the above methods to create a list, but some intermediate operations with streams are `filter()`, where we could remove strings starting with `"s"` for example, `skip(n)` which *skips* the first n elements, or `sorted()` will sort the elements of the stream based on it's natural order. As I said, go and look into streams if you like, there's a lot a good things and useful benefits to using them. 

That's it, we're done. I hope you found something useful, I know I enjoyed writing this and reading the documents to check my facts. If there's anything you'd like to add (to my first Dev.to post, no less!) please do comment below. 

Thanks for reading!