Java initialize list with values

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.

Читайте также:  Php mysql boolean update

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

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.

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.

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

intialize ArrayList with Integer values

intialize ArrayList with float values

ArrayList < Integer >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.

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.

💡 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.

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

Was this post helpful?

You may also like:

Update Value of Key in HashMap in Java

Create Array of Linked Lists in Java

Return ArrayList in Java

Create List with One Element in Java

How to Add Multiple Values for Single Key In HashMap in Java

[Fixed] java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList

Create ArrayList of Objects in Java

How to remove element from Arraylist in java while iterating

Share this

Author

Update Value of Key in HashMap in Java

Table of ContentsUsing the put() Method of HashMap Collection in JavaUsing the compute() Method of HashMap Collection in JavaUsing the merge() Method of the HashMap Collection in JavaUsing the computeIfPresent() Method of The HashMap Collection in JavaUsing the replace() Method of The HashMap Collection in JavaUsing the TObjectIntHashMap Class of Gnu.Trove Package in JavaUsing the […]

Create Array of Linked Lists in Java

Table of ContentsIntroductionLinked List in JavaApplication of Array of Linked ListsCreate Array of Linked Lists in JavaUsing Object[] array of Linked Lists in JavaUsing the Linked List array in JavaUsing the ArrayList of Linked Lists in JavaUsing the Apache Commons Collections Package Introduction In this article, we will look at how to Create an Array […]

Return ArrayList in Java

Table of ContentsReturn ArrayList in Java From a Static MethodReturn ArrayList in Java From a Non-static MethodConclusion This article discusses cases of returning an ArrayList in Java from a method. An ArrayList in Java is a collection of elements of the same data type under a single variable name. In different cases, you can return […]

Create List with One Element in Java

Table of ContentsUsing Collections.singletonList()Using Array.asList() method [ Immuatable list]Using new ArrayList with Array.asList() method [ Mutable list] In this post, we will see how to create List with One Element in java.. Using Collections.singletonList() This is best way to create List with single element if you need an immutable List. [crayon-64b9be3d3167d737443027/] Output [crayon-64b9be3d31684146312787/] If you […]

How to Add Multiple Values for Single Key In HashMap in Java

Table of ContentsHashMapCan HashMap Store Multiple Values AutomaticallyWays to Add Multiple Values for Single Key In HashMap in JavaUsing the Standard LibraryUsing Apache Commons LibraryUsing Google Guava LibraryUsing TreeSet as ValuesUsing a Wrapper ClassUsing Java TuplesUsing compute() Function in JDK 8Conclusion This article discusses the HashMap in Java and how to add multiple values for […]

java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList

[Fixed] java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList

Table of ContentsReason for java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayListFixes for java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayListUse ArrayList’s constructorAssign Arrays.asList() to List reference rather than ArrayList In this post, we will see how to fix java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList. ClassCastException is runtime exception which indicate that code has tried to […]

Источник

How to Initialize an ArrayList in Java – Declaration with Values

Ihechikara Vincent Abba

Ihechikara Vincent Abba

How to Initialize an ArrayList in Java – Declaration with Values

You can use an ArrayList in Java to store and manipulate a collection of similar variables.

An ArrayList is just like an array but offers more flexibility. An ArrayList is more dynamic with the size of the collection, and gives you more control over the elements in a collection.

In this article, you’ll learn how to declare and initialize an ArrayList in Java. You’ll see the different in-built methods that can be used to add, access, modify, and remove elements in an ArrayList .

How To Declare an ArrayList With Values in Java

The terms «declaration» and «initialization» are commonly associated with data structures.

Declaration has to do with creating a data structure, while initialization involves assigning values to the data structure.

Here’s how you can declare an ArrayList in Java:

import java.util.ArrayList; public class ArrayListTut < public static void main(String[] args) < ArrayListpeople = new ArrayList<>(); > >

To make use of an ArrayList , you must first import it from the ArrayList class: import java.util.ArrayList; .

After that, you can create a new ArrayList object. In the code above, we created a new ArrayList object called people .

Note that the data type of the ArrayList is specified with angle brackets: ArrayList .

At this point, we’ve created an ArrayList but it has no elements. You’ll see how to add elements to it in another section.

Alternatively, you can create an ArrayList with values/elements at the point of declaration by using the add method in an initializer block:

import java.util.ArrayList; public class ArrayListTut < public static void main(String[] args) < ArrayListpeople = new ArrayList<>() >; System.out.println(people); // [John, Jane, Doe] > >

How To Add Elements to a Java ArrayList

You can use the add() method to add elements to an ArrayList .

import java.util.ArrayList; public class ArrayListTut < public static void main(String[] args) < ArrayListpeople = new ArrayList<>(); people.add("John"); people.add("Jane"); people.add("Doe"); System.out.println(people); // [John, Jane, Doe] > >

In the code above, we declared an ArrayList called people without any elements.

Using dot notation and the add() method, we added elements to the people collection: people.add(«John») .

How To Access Elements in a Java ArrayList

You can access elements in a Java ArrayList by using the element’s index.

The index of the element will be passed in as a parameter to the get() method. That is:

import java.util.ArrayList; public class ArrayListTut < public static void main(String[] args) < ArrayListpeople = new ArrayList<>(); people.add("John"); people.add("Jane"); people.add("Doe"); System.out.println(people.get(0)); // John > >

In the code above, people.get(0) gets the first element — «John».

Note that the first element has an index of 0 , the second has an index of 1 , and so on.

How To Modify Elements in a Java ArrayList

You can change or modify the value of an element by using the set() method.

The set() method takes in two parameters — the index of the element to be changed and the new value to be assigned to that index.

import java.util.ArrayList; public class ArrayListTut < public static void main(String[] args) < ArrayListpeople = new ArrayList<>(); people.add("John"); people.add("Jane"); people.add("Doe"); people.set(1, "Jade"); System.out.println(people); // [John, Jade, Doe] > >

In the example above, we changed the second element from «Jane» to «Jade» using its index: people.set(1, «Jade») .

How To Remove Elements in a Java ArrayList

You can remove an element by using the remove() method. The method takes in the index of the element to be removed as a parameter. That is:

import java.util.ArrayList; public class ArrayListTut < public static void main(String[] args) < ArrayListpeople = new ArrayList<>(); people.add("John"); people.add("Jane"); people.add("Doe"); people.remove(2); System.out.println(people); // [John, Jane] > >

Using the remove() method, we removed the third element in the collection using the element’s index: people.remove(2); .

Summary

In this article, we talked about the Java ArrayList data structure. It can be used to store a collection of variables.

An ArrayList give you more control over the elements in a collection and has a dynamic size that isn’t fixed on declaration like Java arrays.

We saw how to declare and initialize an ArrayList with values. We also saw different methods for adding, accessing, changing, and removing elements in an ArrayList .

Happy coding! I also write about Java on my blog.

Источник

Initialize List with Values in Java

In this tutorial, we’ll learn different ways to initialize List, ArrayList and LinkedList with values in single line in Java.

Java 8 or earlier

Initialize Immutable List

This is the simplest way to initialize a List:-

/** * Immutable list with inline elements */ ListString> list = Arrays.asList("foo", "bar", "baz");  /** * Immutable list with array */ String[] names =  "foo", "bar" >; ListString> anotherList = Arrays.asList(names);  anotherList.add("baz") // Throw UnsupportedOperationException exception 

The only drawback is that the initalized list is immutable. That means adding or removing elements in the list throw java.lang.UnsupportedOperationException exception.

It is useful when you just need it for iteration and read-only purpose.

Initialize Mutable List

If you want to intialize a mutable list where you can add or remove elements. You wrap immutable list with ArrayList or LinkedList :-

ListString> arrayList = new ArrayList<>(Arrays.asList("foo", "bar")); arrayList.add("baz"); // It works!  ListString> linkedList = new LinkedList<>(Arrays.asList("foo", "bar")); linkedList.remove("foo"); // It works! 
Collections.addAll()

You can also use Collections.addAll() static method to add values to ArrayList or LinkedList

ListString> arrayList = new ArrayListString>(); Collections.addAll(arrayList, "foo", "bar", "baz"); 
Double Brace Initialization

Another way is to making an anonymous inner class with an instance initializer. This is also known as an double brace initialization. However that looks like an overkill to create a inner class just to create an ArrayList or LinkedList

ListString> strings = new ArrayListString>()     add("A");  add("B");  add("C");  > >; 

Java 9 or later

Initialize Immutable List

List.of() is added in Java 9 which can be used to initialize an immutable list with values.

ListString> list = List.of("foo", "bar"); list.add("baz") // Throw UnsupportedOperationException exception 

With Java 10 or later, this can be even more shortened with the var keyword.

var list = List.of("foo", "bar", "baz"); 
Initialize Mutable List

You can also define mutable list with ArrayList or LinkedList wrapper:-

ListString> arrayList = new ArrayList<>(List.of("foo", "bar")); arrayList.add("baz"); // It works!  ListString> linkedList = new LinkedList<>(List.of("foo", "bar")); linkedList.remove("foo"); // It works! 

Using Streams

You can also use Stream API which is more flexible:-

StreamString> strings = Stream.of("foo", "bar", "baz"); 

You can combine two or more Streams like this:-

StreamString> strings = Stream.concat(Stream.of("foo", "bar"), Stream.of("baz", "qux")); 

You can transform a Stream into mutable List or ArrayList like this:-

ListString> list = Stream.of("foo", "bar", "baz").collect(Collectors.toList()); list.remove("baz"); // It works!  ListString> arrayList = Stream.of("foo", "bar").collect(Collectors.toCollection(ArrayList::new)); arrayList.add("baz"); // It works! 

See Also

Ashish Lahoti avatar

Ashish Lahoti is a Software Engineer with 12+ years of experience in designing and developing distributed and scalable enterprise applications using modern practices. He is a technology enthusiast and has a passion for coding & blogging.

Источник

Оцените статью