- Prev Class
- Next Class
- No Frames
- All Classes
- Nested |
- Field |
- Constr |
Method summary, methods inherited from interface java.util. collection, methods inherited from interface java.lang. iterable, method detail, containsall, lastindexof, listiterator, spliterator.
Submit a bug or feature For further API reference and developer documentation, see Java SE Documentation . That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples. Copyright © 1993, 2023, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms . Also see the documentation redistribution policy .
Scripting on this page tracks web page traffic, but does not change the content in any way.
- Java Arrays
- Java Strings
- Java Collection
- Java 8 Tutorial
- Java Multithreading
- Java Exception Handling
- Java Programs
- Java Project
- Java Collections Interview
- Java Interview Questions
- Spring Boot
- Explore Our Geeks Community
- Java Programs - Java Programming Examples
Java Basic Programs
- How to Read and Print an Integer value in Java
- Ways to read input from console in Java
- Java Program to Multiply two Floating-Point Numbers
- Java Program to Swap Two Numbers
- Java Program to Add Two Binary Strings
- Java Program to Add two Complex Numbers
- Java Program to Check if a Given Integer is Odd or Even
- Java Program to Find the Largest of three Numbers
- Java Program to Find LCM of Two Numbers
- Java Program to Find GCD or HCF of Two Numbers
- Java Program to Display All Prime Numbers from 1 to N
- Java Program to Find if a Given Year is a Leap Year
- Java Program to Check Armstrong Number between Two Integers
- Java Program to Check If a Number is Neon Number or Not
- Java Program to Check Whether the Character is Vowel or Consonant
- Java Program for factorial of a number
- Java Program to Find Sum of Fibonacci Series Numbers of First N Even Indexes
- Java Program to Calculate Simple Interest
- Java Program for compound interest
- Java Program to Find the Perimeter of a Rectangle
Java Pattern Programs
- Java Program to Print Right Triangle Star Pattern
- Java Program to Print Left Triangle Star Pattern
- Java Program to Print Pyramid Number Pattern
- Java Program to Print Reverse Pyramid Star Pattern
- Java Program to Print Upper Star Triangle Pattern
- Java Program to Print Mirror Upper Star Triangle Pattern
- Java Program to Print Downward Triangle Star Pattern
- Java Program to Print Mirror Lower Star Triangle Pattern
- Java Program to Print Star Pascal’s Triangle
- Java Program to Print Diamond Shape Star Pattern
- Java Program to Print Square Star Pattern
- Java Program to Print Pyramid Star Pattern
- Java Program to Print Spiral Pattern of Numbers
- Java Program to Convert Binary to Octal
- Java Program to Convert Octal to Decimal
- Java Program For Decimal to Octal Conversion
- Java Program For Hexadecimal to Decimal Conversion
- Java Program For Decimal to Hexadecimal Conversion
- Java Program for Decimal to Binary Conversion
- Boolean toString() method in Java with examples
- Convert String to Double in Java
- Java Program to Convert Double to String
- Java Program to Convert String to Long
- Java Program to Convert Long to String
- Java Program For Int to Char Conversion
Java Conversion Programs
- Classes and Objects in Java
- Abstract Class in Java
- Java Singleton Class
- Interfaces in Java
- Encapsulation in Java
- Inheritance in Java
- Abstraction in Java
- Difference Between Data Hiding and Abstraction in Java
- Polymorphism in Java
- Method Overloading in Java
- Overriding in Java
- Super Keyword in Java
- 'this' reference in Java
Java Classes and Object Programs
- Java main() Method - public static void main(String args)
- Difference between static and non-static method in Java
- HashTable forEach() method in Java with Examples
- StringBuilder toString() method in Java with Examples
- StringBuffer codePointAt() method in Java with Examples
- How compare() method works in Java
- Short equals() method in Java with Examples
- Difference Between next() and hasNext() Method in Java Collections
- What does start() function do in multithreading in Java?
- Difference between Thread.start() and Thread.run() in Java
- Java Program for Linear Search
Java Methods Programs
- Check if a value is present in an Array in Java
- Java Program to find largest element in an array
- Arrays.sort() in Java with examples
- Java Program to Sort the Array Elements in Descending Order
- Java Program to Sort the Elements of an Array in Ascending Order
- Remove duplicates from Sorted Array
- Java Program to Merge Two Arrays
- Java Program to Check if two Arrays are Equal or not
Java Searching Programs
- Array Copy in Java
- Java Program For Array Rotation
Java 1-D Array Programs
- Java Program to Add two Matrices
- Sorting a 2D Array according to values in any given column in Java
- Java Program to Find Transpose of Matrix
- Java Program to Find the Determinant of a Matrix
- Java Program to Find the Normal and Trace of a Matrix
- Java Program to Print Boundary Elements of the Matrix
- Java Program to Rotate Matrix Elements
- Java Program to Compute the Sum of Diagonals of a Matrix
- Java Program to Interchange Elements of First and Last in a Matrix Across Rows
- Java Program to Interchange Elements of First and Last in a Matrix Across Columns
Java 2-D Arrays (Matrix) Programs
- Reverse a string in Java
- Java Program to Reverse a String using Stack
- Sort a String in Java (2 different ways)
- Swapping Pairs of Characters in a String in Java
- Check if a given string is Pangram in Java
- Print first letter of each word in a string using regex
- Java Program to Determine the Unicode Code Point at Given Index in String
- Remove Leading Zeros From String in Java
- Compare two Strings in Java
- Compare two strings lexicographically in Java
- Java program to print Even length words in a String
- Insert a String into another String in Java
Java String Programs
Initializing a list in java.
- How to Find a Sublist in a List in Java?
- Min and Max in a List in Java
- Split a List into Two Halves in Java
- How to remove a SubList from a List in Java
- How to Remove Duplicates from ArrayList in Java
- How to sort an ArrayList in Ascending Order in Java
- Get first and last elements from ArrayList in Java
- Convert a List of String to a comma separated String in Java
- How to Add Element at First and Last Position of LinkedList in Java?
- Find common elements in two ArrayLists in Java
- Remove repeated elements from ArrayList in Java
Java List Programs
- Java Program to Display Current Date and Time
- Java Program to Display Time in Different Country Format
- How to Convert Local Time to GMT in Java?
- Java Program to Create a New File
- Java Program to Create a Temporary File
- Java Program to Rename a File
- Java Program to Make a File Read-Only
- Comparing Path of Two Files in Java
- Different Ways to Copy Content From One File to Another File in Java
- Java Program to Print all the Strings that Match a Given Pattern from a File
- Java Program to Append a String in an Existing File
Java Date and Time Programs
- Java Program to Traverse in a Directory
- Java Program to Get the Size of a Directory
- Java Program to Delete a directory
Java File Programs
- Java Program to Find Current Working Directory
- Java Program to List all Files in a Directory and Nested Sub-Directories
- Exceptions in Java
- Types of Errors in Java with Examples
- Java Program to Handle the Exception Hierarchies
- Java Program to Handle the Exception Methods
- Java Program to Handle Checked Exception
- Java Program to Handle Unchecked Exception
Java Directory Programs
- Thread Interference and Memory Consistency Errors in Java
- Collections in Java
- How to Print a Collection in Java?
- Java Program to Compare Elements in a Collection
- Java Program to Get the Size of Collection and Verify that Collection is Empty
Java Exceptions and Errors Programs
- Java Program to Change a Collection to an Array
- Convert an Array into Collection in Java
- How to Replace a Element in Java ArrayList?
- Java Program to Rotate Elements of the List
- How to iterate any Map in Java
- Thread isAlive() Method in Java With Examples
- How to Temporarily Stop a Thread in Java?
Java Collections Programs
- Program to Print Fibonacci Series in Java
- How to convert LinkedList to Array in Java?
- Program to Convert a Vector to List in Java
- Convert a String to a List of Characters in Java
- Convert an Iterator to a List in Java
- Program to Convert List to Map in Java
- Program to Convert List to Stream in Java
- Convert List to Set in Java
- Java Program to Convert InputStream to String
- Convert Set of String to Array of String in Java
Java Multithreading Programs
Java more java programs.
The Java.util.List is a child interface of Collection . It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. List Interface is implemented by ArrayList , LinkedList , Vector and Stack classes.
List is an interface, and the instances of List can be created in the following ways:
Below are the following ways to initialize a list:
Using List.add() method
Since list is an interface, one can’t directly instantiate it. However, one can create objects of those classes which have implemented this interface and instantiate them.
Few classes which have implemented the List interface are Stack, ArrayList, LinkedList, Vector etc.
Double Brace Initialization can also be used to do the above work.
Arrays.asList() creates an immutable list from an array. Hence it can be used to instantiate a list with an array.
Using Collections class methods
There are various methods in Collections class that can be used to instantiate a list. They are:
Collections class has a static method addAll() which can be used to initialize a list. Collections.addAll() take in any number of elements after it is specified with the Collection in which the elements are to be inserted.
Collections.unmodifiableList() returns a list which can’t be altered i.e. it can neither add or delete an element. Any attempt to modify the list will result in an UnsupportedOperationExample.
Collections.singletonList() returns an immutable list consisting of one element only.
Using Java 8 Stream
With the introduction of Stream and functional programming in Java 8, now one can construct any stream of objects and then collect them as a list.
Using Java 9 List.of()
Java 9 introduced List.of() method which takes in any number of arguments and constructs a compact and unmodifiable list out of them.
Please Login to comment...
- Java - util package
- Technical Scripter
Please write us at contrib[email protected] to report any issue with the above content
Improve your Coding Skills with Practice
How to Initialize a Java List – List of String Initialization in Java
Java is a popular programming language widely used for developing robust and scalable applications. One of the essential data structures in Java is a list, which allows developers to store and manipulate a collection of elements.
Initializing a list in Java is a crucial step in the development process as it defines the initial state of the list and prepares it for further operations. There are various ways to initialize a list in Java, and the choice depends on the specific requirements of the project.
In this article, we will explore the different methods to initialize a Java list and provide examples to illustrate their usage. Whether you are a beginner or an experienced Java developer, this guide will help you understand the best practices for initializing a Java list and improving the performance of your application.
In Java, there are different ways to initialize a list:
- Using the ArrayList constructor.
- Using the add() method.
- Using the Arrays.asList() method.
- Using the Stream.of() method.
Let's take a deep look into these methods.
How to Initialize a List Using the ArrayList Constructor
In Java, the ArrayList class is a dynamic array implementation of the List interface, allowing elements to be added and removed from the list as needed. The ArrayList class provides several constructors for creating an instance of the class.
The syntax for creating an ArrayList object with no initial capacity is:
The constructor with no arguments creates an empty list with an initial capacity of 10 elements. If the list grows beyond that capacity, the ArrayList class automatically increases the capacity by creating a new array with a larger size and copying the elements from the old array to the new array.
Alternatively, we can create an ArrayList object with an initial capacity using the constructor with a single integer argument:
where capacity is the initial capacity of the list.
To initialize a List with values, we can use the constructor that takes a Collection as an argument. We can pass any collection object that implements the Collection interface to this constructor, such as another ArrayList or a LinkedList . The elements in the collection are added to the new ArrayList in the order they appear in the collection.
Here's an example of how to create an ArrayList and initialize it with values using the constructor that takes a Collection :
In this example, we create an array of integers and then pass it to the Arrays.asList() method to create a List object. We then pass this List object to the ArrayList constructor to create a new ArrayList with the same elements as the original array. Finally, we print the contents of the list using the System.out.println() method.
How to Initialize a List Using the add() Method
The add() method is a commonly used method in Java that is used to add elements to a collection or list. This method is available for several types of collections in Java, including List, Set, and Map. The add() method takes a single argument, which is the element that needs to be added to the collection.
When it comes to adding elements to a Java List, the add() method is particularly useful. Lists in Java are ordered collections that can contain duplicates. The add() method can be used to add elements to the end of a list, which makes it a convenient way to initialize a list with some initial values.
Here is an example of how to use the add() method to initialize a Java list:
In this example, we first create a new ArrayList called myList . We then use the add() method to add three strings ("apple", "banana", and "cherry") to the end of the list. Finally, we print the contents of the list using the System.out.println() method.
When we run this program, the output will be:
How to Initialize a List Using the Arrays.asList() Method
The Arrays.asList() method is a built-in method in Java that converts an array into a List. This method takes an array as an argument and returns a List object. The List object returned by the Arrays.asList() method is a fixed-size list, which means that we cannot add or remove elements from it.
To use the Arrays.asList() method to initialize a Java List, we can follow these steps:
First, declare an array of elements that we want to initialize the list with. For example, let's say we want to initialize a list with three elements: "apple", "banana", and "orange". We can declare an array as follows:
Then call the Arrays.asList() method and pass the array as an argument. This will return a List object containing the elements of the array.
We can now use the fruitList object to access the elements of the list. For example, we can iterate over the list and print each element:
It is important to note that the Arrays.asList() method does not create a new List object, but rather returns a view of the original array as a List object. This means that if we modify the original array, the changes will be reflected in the List object as well. For example:
In the above example, we modified the first element of the fruits array to "pear". When we access the first element of the fruitList object, we get "pear" as well, because fruitList is just a view of the fruits array.
How to Initialize a List Using the Stream.of() Method
The Stream.of() method is a convenient method provided by Java 8 and higher versions in the java.util.stream package. It is used to create a stream of elements of any type, including primitive types, arrays, and objects. This method takes one or more arguments and returns a stream consisting of those arguments.
Here is the syntax for the Stream.of() method:
where T is the type of the elements in the stream, and t1 through tn are the elements to be included in the stream.
To initialize a Java list using the Stream.of() method, we can follow these steps:
First, import the java.util.stream package.
Then create a list of the desired type using the ArrayList constructor, for example:
Initialize the list using the Stream.of() method, passing in the desired elements as arguments, and then use the collect() method to collect the stream elements into the list, for example:
We can then print the list to verify its contents.
In conclusion, initializing a Java List is a common task in Java programming, and there are several ways to do it.
By following the steps outlined in this article, we can easily create and initialize a Java List with the desired elements using the Stream.of() method. This approach is concise and flexible, and it can be especially useful when we need to initialize a list with a small number of elements.
Let's connect on Twitter and on LinkedIn . You can also subscribe to my YouTube channel.
Hello 👋 my name is Shittu Olumide; I am a software engineer and technical writer, compassionate about the community and its members.
If you read this far, thank the author to show them you care. Say Thanks
Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started
Home » Java » How to Initialize a List Inline in Java
How to Initialize a List Inline in Java
A guide containing examples of creating and initializing Java Lists inline .
Creating a Simple Java ArrayList
At the very basic, we can create an empty Java List using a constructor and add elements. Example of creating an empty Java List and adding elements to it .
Creating an ArrayList using a Collection
Alternatively, we can initialize an ArrayList inline using another collection in the ArrayList constructor. The constructor creates a mutable instance of ArrayList containing all the elements from the given collection.
First, we initialized a HashSet instance in Inline and used it in the ArrayList constructor.
Creating an ArrayList using Stream Collectors
The Stream interface offers the toList() method, which is an abstraction to collect the Stream elements in the form of an immutable Java List. The toList() method returns a new List containing all Stream elements.
Example of Stream toList() to create a new List containing Stream elements .
Alternatively, we can use toCollection() method of the Collectors class to provide a List instance. The toCollection() collects all Stream elements into the given List and returns it.
We used an ArrayList constructor reference to provide an empty ArrayList to collect the elements.
Creating an ArrayList using Anonymous Subclass
Another way to create and initialize an ArrayList inline is to use an anonymous subclass .
Although this looks simple, we should avoid using it as it has a lot of overhead and potential memory leak issues.
Create an Immutable ArrayList using Collections
The Java Collections class provides the unmodifiableList() , a factory method, to create an immutable ArrayList containing all the elements of the given Collection or List . Example of creating an immutable ArrayList inline using another Collection .
As the resulting List is immutable, we cannot add, remove or modify its elements.
Creating a Singleton ArrayList
The singletonList() method of the Java Collections class provides a factory method to create an immutable ArrayList instance containing the given element.
A singleton ArrayList instance contains one and only one element. As it is immutable, we cannot modify it once it is created.
Creating an Immutable ArrayList using Factory Methods
Java 9 introduced a factory method in the List class that returns an instance of an immutable ArrayList containing the given element. This is the most straightforward way of creating and initiating an ArrayList in the same line.
Example of using List factory method to initialize an immutable ArrayList inline .
Creating an ArrayList using Arrays Class
The Arrays class in Java supports creating an ArrayList from a Java array. Let’s understand two ways of using the Arrays class to create and initialize a Java ArrayList inline.
Create an ArrayList using Another Array
Let’s create and initialize an immutable ArrayList instance using an existing Java array.
Although the ArrayList we create here is immutable, it is just a view on the original Java Array. That means if we modify the Array, we can see the change is reflected in the immutable List .
Let’s modify an element in the Array and print the Array and the List.
As the output shows, changes to the underlying Array are also reflected in the List. However, the List itself is immutable.
Create an ArrayList using Inline Array
Another version of the Java Array ‘s asList() method accepts n elements and returns a new ArrayList containing those elements.
Please note that the asList() method internally creates an Array of the given elements, and the Array backs the ArrayList it returns.
This article demonstrated various ways of creating an ArrayList instance and adding elements in the same line. We covered different examples of an inline initialization of Java ArrayList , including using basic Java factory methods, Stream collectors, and using utility classes like Arrays and Collections.
Please refer to our GitHub Repository for the complete source code of the examples .
Java List vs ArrayList
List is an interface whereas ArrayList is the implementation class of List.
How to create List
The ArrayList and LinkedList classes provide the implementation of List interface. Let's see the examples to create the List:
In short, you can create the List of any type. The ArrayList<T> and LinkedList<T> classes are used to specify the type. Here, T denotes the type.
Java List Example
Let's see a simple example of List where we are using the ArrayList class as the implementation.
How to convert Array to List
We can convert the Array to List by traversing the array and adding the element in list one by one using list.add() method. Let's see a simple example to convert array elements into List.
How to convert List to Array
We can convert the List to Array by calling the list.toArray() method. Let's see a simple example to convert list elements into array.
Get and Set Element in List
The get() method returns the element at the given index, whereas the set() method changes or replaces the element.
How to Sort List
There are various ways to sort the List, here we are going to use Collections.sort() method to sort the list element. The java.util package provides a utility class Collections which has the static method sort(). Using the Collections.sort() method, we can easily sort any List.
Java ListIterator Interface
ListIterator Interface is used to traverse the element in a backward and forward direction.
ListIterator Interface declaration
Methods of java listiterator interface:, example of listiterator interface, example of list: book.
Let's see an example of List where we are adding the Books.
ArrayList in Java
LinkedList in Java
Difference between ArrayList and LinkedList
Difference between Array and ArrayList
When to use ArrayList and LinkedList in Java
Difference between ArrayList and Vector
How to Compare Two ArrayList in Java
How to reverse ArrayList in Java
How to make ArrayList Read Only
Difference between length of array and size() of ArrayList in Java
How to Synchronize ArrayList in Java
How to convert ArrayList to Array and Array to ArrayList in java
Array vs ArrayList in Java
How to Sort Java ArrayList in Descending Order
How to remove duplicates from ArrayList in Java
- Send your Feedback to [email protected]
Help Others, Please Share
Learn Latest Tutorials
Python Design Patterns
B.Tech / MCA
JavaTpoint offers too many high quality services. Mail us on h [email protected] , to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- Graphic Designing
- Digital Marketing
- On Page and Off Page SEO
- Content Development
- Corporate Training
- Classroom and Online Training
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected] . Duration: 1 week to 2 week
Initialize a list in Java in a single line with specific value
This post will discuss how to initialize a list in Java in a single line with the specified value.
A naive solution is to call the List.add() method n times in a loop, where n is the specified size of the list. This works fine, but there are better ways, as discussed below:
1. Using Collections.nCopies() method
Java collection framework has provided the Collections.nCopies() method, which returns an immutable list consisting of the specified copies of the specified object. The object allocated by this method holds a single reference to the specified object; hence its memory consumption is very less.
Download Run Code
2. Using Java 8 Stream
We can also use Java 8 Stream for this. The idea is to use the Stream.generate() method, which takes a Supplier. In the following example, we have created an infinite stream of empty character sequence, which is limited by using the limit() method. Finally, each element is mapped to the specified value and collected in an immutable list.
The above approach can work on any object or a primitive value. If we have a list of Integer, we can do something like:
[1, 1, 1, 1, 1]
This is equivalent to:
3. Using intermediate array
Well, this is not a single liner, but worth mentioning. The idea is to create an array of the specified size and use Arrays.fill() to initialize it by the given value. Then we pass this array to the Arrays.asList() method to get an immutable list.
Here’s how we can do the same in a single line using Java 8 Stream, which can work on any object.
We can also use Arrays.stream() or Stream.of() with map() method.
Please note that all the above-mentioned methods produce an immutable list. To get a mutable instance, we need to wrap the list using the ArrayList constructor. For instance,
That’s all about initializing a list in Java in a single line with the specified value.
Rate this post
Average rating 4.43 /5. Vote count: 7
No votes so far! Be the first to rate this post.
We are sorry that this post was not useful for you!
Tell us how we can improve this post?