Initializing a List in Java10 Sept 2024 | 6 min read One of Collection's derived interfaces is Java.util.List. It is an ordered group of objects that allows for the storing of duplicate values. List enables positional access and element insertion since it maintains the insertion order. The Vector, Stack, LinkedList, and ArrayList classes to implement the List Interface. 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. List is an interface, and the following methods can be used to create instances of List: The following are the different approaches to initialize list.
Approach: Using List.add() methodList cannot be instantiated directly because it is an interface. On the other hand, objects of the classes that have defined this interface can be created and instantiated. Add(): 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. A few examples of classes that have implemented the List interface include Vector, LinkedList, Stack, and ArrayList. Syntax: There are two cases in this approach.
Case 1: General methodImplementation: FileName: GeneralMethod.java Output: The ArrayList is : [10, 30] The LinkedList is : [20, 40] The Stack is : [30, 10] Case 2: Double Brace InitializationImplementation: FileName: Doublebrace.java Output: The ArrayList is : [10, 30] The LinkedList is : [20, 40] The Stack is : [30, 10] Approach: Using Arrays.asList()There are mainly two cases present in this approach.
Case 1: By creating an Immutable ListWe can use Arrays.asList() to convert an array into an immutable list. So, it is possible to utilise an array to instantiate a list. Implementation: FileName: ImmutableList.java Output: The List is : [10, 20, 30] The List is : [60, 20, 50] Case 2: By creating a Mutable ListSyntax: List<Integer> list_1=new ArrayList<>(Arrays.asList(element 1, element 2, element 3)); Implementation: FileName: Mutablelist.java Output: The first created List : [10, 20, 30] The Modified list is given by : [10, 20, 30, 50, 40] Approach: Using Collections class methodsA list can be instantiated using a variety of methods in the Collections class. They are as follows:
Case 1: Using Collections.addAll()The static function addAll() in the Collections class can be used to initialise a list. Any amount of elements can be entered into Collections.addAll() once the Collection in which the elements are to be inserted is defined. Syntax: Implementation: FileName: CollectionsAddAll.java Output: The List is given by : [10, 20, 30, 40] Case 2: By using Collections.unmodifiableList()The list returned by Collections.unmodifiableList() cannot be changed; that is, no element can be added or removed. An UnsupportedOperationExample will be generated if there is any attempt to alter the list. Syntax: Implementation: FileName: UnmodifableList.java Output: The List is given by : [10, 20, 30] Case 3: By using Collections.singletonList()Collections.singletonList() returns back an unchangeable list with just one element. Syntax: Implementation: FileName: SingletonList.java Output: The List is given by : [10] Approach: Using Java 8 StreamAs of Java 8, one can create any stream of objects and then compile them into a list by using the addition of Stream and functional programming. 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. 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. Syntax: Implementation:FileName: java8Stream.java Output: The List using Syntax 1 is given by : [10, 20, 30, 40] The List using Syntax 2 is given by : [10, 20, 30, 40] The List using Syntax 3 is given by : [10, 20, 30, 40] Approach: Using Java 9 List.of()The introduction of Java 9 The List.of() function creates a reduced to, immutable list from any number of arguments it receives. 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. Syntax: Implementation:FileName: Java9Example.java Output: The List is given by : [10, 20, 30, 40] Next TopicNumber Guessing Game in Java |
In the world of Java programming, data structures play a crucial role in storing and manipulating data efficiently. Two commonly used data structures for this purpose are vectors and arrays. While both are used to store collections of elements, they have distinct differences that make them...
13 min read
QuickSort is a highly efficient divide-and-conquer sorting algorithm that recursively partitions an array into smaller subarrays. Multi-threading allows parallel execution of sorting on different partitions, utilizing multiple processor cores to reduce execution time. It allows the concurrent execution of two or more parts of the program for...
5 min read
In Java, inheritance enables a class to adopt behaviors and functions from another class. The class from which the functionalities and behaviours are inherited is known as the base class or parent class or superclass. The receiver class is often known as a child class,...
4 min read
In Java, evaluating mathematical expressions can sometimes be a complex and error-prone task. Manually parsing and calculating expressions can lead to tedious and lengthy code. To simplify this process, we can leverage the power of EvalEx (Evaluate Expression) Java, a lightweight Java library that provides an...
5 min read
One of the most popular programming problems is to create every conceivable string combination. There are a few ways to do this with Java, including repetition, and recursion. We will examine many approaches to producing every possible combination of a given string in this section. Method 1:...
5 min read
? Java is recognised for its ability to construct and manipulate objects in object-oriented programming. An object is an instance of a class, and in the Java programming language, instances are fundamental. In this post, we'll examine what a Java instance is and how classes and objects...
4 min read
Javac command is usually used to check whether the Java is installed in our system or not. When the Java is not installed in our system and we try to run Javac command, we get Javac command not found or Java is not Recognized. We can...
2 min read
What is Java? Java is a high-level, general-purpose, object-oriented, and secure programming language developed by James Gosling at Sun Microsystems, Inc. in 1991. It is formally known as OAK. In 1995, Sun Microsystem changed the name to Java. In 2009, Sun Microsystem takeover by Oracle Corporation. Because...
8 min read
Generally, all the users need to enter a username and password to log in to any application. Otherwise, the application page will not open. SAML stands for Security Assertion Markup Language. To understand what SAML is, we need to know what SSO is. SSO (Single Sign-on) Single sign-on...
17 min read
Palindromic string partitioning is the process of separating a string into different parts. of strings so that each string is a palindrome. A palindrome is a sequence of characters that can be read from back to front (such as "race car"). This problem has found application...
5 min read
We request you to subscribe our newsletter for upcoming updates.
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India