Sitelet https://java2blog.com/initialize-arraylist-values-java/

Initialize ArrayList with values in Java

In this article, we will learn to initialize ArrayList with values in Java.
ArrayList is an implementation class of List interface in Java. It is used to store elements. It is based on a dynamic array concept that grows accordingly.
We can Initialize ArrayList with values in several ways. Let’s see some of them with examples.
[toc]

Using Arrays.asList()

We can use Arrays.asList() method and pass it to ArrayList’s constructor to initialize ArrayList with values in java. This approach is useful when we already have data collection.

Initialize ArrayList with String values

import java.util.Arrays;
import java.util.List;
public class Main
{   
    public static void main(String args[]) 
    {
        ArrayList list = new ArrayList<>(Arrays.asList(
                "Apple",
                "Mango",
                "Orange"
                ));
        for (String item : list) {
            System.out.println(item);
        }
    }
}

Output:

Apple
Mango
Orange

When you pass Arrays.asList() to ArrayList constructor, you will get ArrayList object and you can modify the ArrayList the way you want.

💡 Did you know?

If you are using Array.asList() without ArrayList constructor to initialize list, then You can not structurally modify list after creating it.

import java.util.Arrays;
import java.util.List;
public class Main
{   
    public static void main(String args[]) 
    {
        List list = Arrays.asList(new String[]{
                "Apple",
                "Mango",
                "Orange"
                });
        list.add("Banana");     
        for (String item : list) {
            System.out.println(item);
        }
    }
}

Output:

Exception in thread “main” java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:148)
at java.util.AbstractList.add(AbstractList.java:108)
at Main.main(Main.java:13)

Although you can use list.set() method to change elements.

import java.util.Arrays;
import java.util.List;
public class Main
{   
    public static void main(String args[]) 
    {
        List list = Arrays.asList(new String[]{
                "Apple",
                "Mango",
                "Orange"
                });
        list.set(1,"Banana");       
        for (String item : list) {
            System.out.println(item);
        }
    }
}

Output:

Apple
Banana
Orange

As you can see, 2nd element of the list changed from Mango to Banana

intialize ArrayList with Integer values

ArrayList integerlist = new ArrayList<>(Arrays.asList(10,20,30,40,50));

intialize ArrayList with float values

ArrayList integerlist = new ArrayList<>(Arrays.asList(10.2f,20.4f,30.2f,40.9f,50.4f));

Using Stream in Java 8

If you are working with Java 8 or higher version, then we can use of() method of Stream to initialize an ArrayList in Java. See the example below.

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main
{   
    public static void main(String args[]) 
    {
        List list = Stream.of(
                "Apple",
                "Mango",
                "Orange"
                ).collect(Collectors.toList());
        for (String item : list) {
            System.out.println(item);
        }
    }
}

Output

Apple
Mango
Orange

You can add or remove element from the list with this approach.

Using Factory Method in java 9

In Java 9, Java added some factory methods to List interface to create immutable list in Java. It can be used to initialize ArrayList with values in a single line statement.

import java.util.List;
public class Main
{   
    public static void main(String args[]) 
    {
        List list = List.of(
                "Apple",
                "Mango",
                "Orange"
                );
        for (String item : list) {
            System.out.println(item);
        }
    }
}

Output

Apple
Mango
Orange

💡 Did you know?

As the list is immutable, you can not add/remove new element and you can not use list'set() method to change elements.

Using double braces

Here is another approach to initialize ArrayList with values in Java, but it is not recommended because it creates an anonymous class internally that takes to verbose code and complexity.

import java.util.List;
import java.util.ArrayList;
public class Main
{   
    public static void main(String args[]) 
    {
        List list = new ArrayList<>() {{
            add("Apple");
            add("Mango");
            add("Orange");
        }};
        for (String item : list) {
            System.out.println(item);
        }
    }
}

Output

Apple
Mango
Orange

That’s all about how to Initialize ArrayList with Values in Java.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.