Mục lục bài viết

Mẹo Hướng dẫn Add List 2022

Cập Nhật: 2022-01-08 07:53:06,Bạn Cần kiến thức và kỹ năng về Add List. You trọn vẹn có thể lại Comments ở phía dưới để Admin đc lý giải rõ ràng hơn.

570

This Java List Tutorial Explains How to Create, Initialize and Print Lists in Java. The tutorial also Explains List of Lists with Complete Code Example:

Tóm lược đại ý quan trọng trong bài

  • List In Java
  • Create & Declare List
  • Initialize Java List
  • List Example
  • Printing List
  • List Converted To An Array
  • Using Java 8 Streams
  • List Of Lists
  • Frequently Asked Questions
  • Recommended Reading

This tutorial will introduce you to the data structure list which is one of the basic structures in the Java Collection Interface.

A list in Java is a sequence of elements according to an order. The List interface of java.util package is the one that implements this sequence of objects ordered in a particular fashion called List.

=> Check ALL Java Tutorials Here.

Just like arrays, the list elements can also be accessed using indices with the first index starting at 0. The index indicates a particular element at index i i.e. it is i elements away from the beginning of the list.

Some of the characteristics of the list in Java include:

  • Lists can have duplicate elements.
  • The list can also have null elements.
  • Lists tư vấn generics i.e. you can have generic lists.
  • You can also have mixed objects (objects of different classes) in the same list.
  • Lists always preserve insertion order and allow positional access.

What You Will Learn:

  • List In Java
    • Create & Declare List
    • Initialize Java List
      • #1) Using The asList Method
      • #2) Using List.add()
      • #3) Using Collections Class Methods
      • #4) Using Java8 Streams
      • #5) Java 9 List.of() Method
    • List Example
    • Printing List
      • #1) Using For Loop/Enhanced For Loop
      • #2) Using The toString Method
    • List Converted To An Array
    • Using Java 8 Streams
    • List Of Lists
    • Frequently Asked Questions
  • Conclusion
    • Recommended Reading

List In Java

The Java List interface is a sub-type of the Java Collection interface. This is the standard interface that inherits the Collection interface of Java.

Given below is a class diagram of the Java List interface.

Java List Class Diagram

As shown in the above class diagram, the Java list interface extends from the Collection interface of java.util package which in turn extends from the Iterable interface of the java.util package. The class AbstractList provides the skeletal implementation of the List interface.

The classes LinkedList, Stack, Vector, ArrayList, and CopyOnWriteArrayList are all the implementation classes of List interface that are frequently used by programmers. Thus there are four types of lists in Java i.e. Stack, LinkedList, ArrayList, and Vector.

Hence, when you have to implement list Interface, you can implement any of the above list type class depending on the requirements. To include the functionality of the list interface in your program, you will have to import the package java.util.* that contain list interface and other classes definitions as follows:

import java.util.*;

Create & Declare List

We have already stated that List is an interface and is implemented by classes like ArrayList, Stack, Vector and LinkedList. Hence you can declare and create instances of the list in any one of the following ways:

List linkedlist = new LinkedList();
List arrayList = new ArrayList();
List vec_list = new Vector();
List stck_list = new Stack();

As shown above, you can create a list with any of the above classes and then initialize these lists with values. From the above statements, you can make out that the order of elements will change depending on the class used for creating an instance of the list.

For Example, for a list with stack class, the order is Last In, First Out (LIFO).

Initialize Java List

You can make use of any of the methods given below to initialize a list object.

#1) Using The asList Method

The method asList () is already covered in detail in the Arrays topic. You can create an immutable list using the array values.

The general syntax is:

List listname = Arrays.asList(array_name);

Here, the data_type should match that of the array.

The above statement creates an immutable list. If you want the list to be mutable, then you have to create an instance of the list using new and then assign the array elements to it using the asList method.

This is as shown below:

List listname = new ArrayList (Arrays.asList(array_name));

Lets implement a program in Java that shows the creation and initialization of the list using the asList method.

import java.util.*;
public class Main
{
public static void main(String[] args)
//array of strings
String[] strArray = “Delhi”, “Mumbai”, “Kolkata”, “Chennai”;
//initialize an immutable list from array using asList method
List mylist = Arrays.asList(strArray);
//print the list
System.out.println(“Immutable list:”);
for(String val : mylist)
System.out.print(val + ” “);

System.out.println(“n”);
//initialize a mutable list(arraylist) from array using asList method
List arrayList = new ArrayList(Arrays.asList(strArray));
System.out.println(“Mutable list:”);
//add one more element to list
arrayList.add(“Pune”);
//print the arraylist
for(String val : arrayList)
System.out.print(val + ” “);

Output:

In the above program, we have created the immutable list first using the asList method. Then, we create a mutable list by creating an instance of ArrayList and then initializing this ArrayList with values from the array using the asList method.

Note that as the second list is mutable, we can also add more values to it.

#2) Using List.add()

As already mentioned, as the list is just an interface it cannot be instantiated. But we can instantiate classes that implement this interface. Therefore to initialize the list classes, you can use their respective add methods which is a list interface method but implemented by each of the classes.

If you instantiate a linked list class as below:

List llist = new LinkedList ();

Then, to add an element to a list, you can use the add method as follows:

llist.add(3);

There is also a technique called Double brace initialization in which the list is instantiated and initialized by calling the add method in the same statement.

This is done as shown below:

List llist = new LinkedList () add(1); add(3);;

The above statement adds the elements 1 and 3 to the list.

The following program shows the initializations of the list using the add method. It also uses the double brace initialization technique.

import java.util.*;
public class Main
public static void main(String args[])
// ArrayList.add method
List str_list = new ArrayList();
str_list.add(“Java”);
str_list.add(“C++”);
System.out.println(“ArrayList : ” + str_list.toString());
// LinkedList.add method
List even_list = new LinkedList();
even_list.add(2);
even_list.add(4);
System.out.println(“LinkedList : ” + even_list.toString());
// double brace initialization – use add with declaration & initialization
List num_stack = new Stack() add(10);add(20); ;
System.out.println(“Stack : ” + num_stack.toString());

Output:

This program has three different list declarations i.e. ArrayList, LinkedList, and Stack.

ArrayList and LinkedList objects are instantiated and then the add methods are called to add elements to these objects. For stack, double brace initialization is used in which the add method is called during the instantiation itself.

#3) Using Collections Class Methods

The collections class of Java has various methods that can be used to initialize the list.

Some of the methods are:

  • addAll

The general syntax for collections addAll method is:

List listname = Collections.EMPTY_LIST;
Collections.addAll(listname = new ArrayList(), values);

Here, you add values to an empty list. The addAll method takes the list as the first parameter followed by the values to be inserted in the list.

  • unmodifiableList()

The method unmodifiableList() returns an immutable list to which the elements cannot be added nor deleted.

The general syntax of this method is as follows:

List listname =
Collections.unmodifiableList(Arrays.asList(values));

The method takes list values as parameters and returns a list. If at all you try to add or delete any element from this list, then the compiler throws an exception UnsupportedOperationException.

  • singletonList()

The singletonList method returns a list with a single element in it. The list is immutable.

The general syntax for this method is:

List listname = Collections.singletonList(value);

The following Java program demonstrates all the three methods of the Collections class discussed above.

import java.util.*;
public class Main
public static void main(String args[])

// empty list
List list = new ArrayList();
// Instantiating list using Collections.addAll()
Collections.addAll(list, 10, 20, 30, 40);
// Print the list
System.out.println(“List with addAll() : ” + list.toString());
// Create& initialize the list using unmodifiableList method
List intlist = Collections.unmodifiableList(
Arrays.asList(1,3,5,7));
// Print the list
System.out.println(“List with unmodifiableList(): ” + intlist.toString());
// Create& initialize the list using singletonList method
List strlist = Collections.singletonList(“Java”);
// Print the list
System.out.println(“List with singletonList(): ” + strlist.toString());

Output:

#4) Using Java8 Streams

With the introduction of streams in Java 8, you can also construct a stream of data and collect them in a list.

The following program shows the creation of a list using stream.

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main
public static void main(String args[])

// Creating a List using toList Collectors method
List list1 = Stream.of(“January”, “February”, “March”, “April”, “May”)
.collect(Collectors.toList());
// Print the list
System.out.println(“List from Java 8 stream: ”
+ list1.toString());

Output:

The above program collects the stream of string into a list and returns it. You can also use the other Collectors methods like toCollection, unmodifiableList etc. apart from asList in the collect function.

#5) Java 9 List.of() Method

A new method is introduced in Java 9, List.of() which takes any number of elements and constructs a list. The list constructed is immutable.

import java.util.List;
public class Main
public static void main(String args[])
// Create a list using List.of()
List strList = List.of(“Delhi”, “Mumbai”, “Kolkata”);
// Print the List
System.out.println(“List using Java 9 List.of() : ” + strList.toString());

Output:

List Example

Given below is a complete example of using a list interface and its various methods.

import java.util.*;
public class Main
public static void main(String[] args)

// Creating a list
List intList = new ArrayList();
//add two values to the list
intList.add(0, 10);
intList.add(1, 20);
System.out.println(“The initial List:n” + intList);
// Creating another list
List cp_list = new ArrayList();
cp_list.add(30);
cp_list.add(40);
cp_list.add(50);
// add list cp_list to intList from index 2
intList.addAll(2, cp_list);
System.out.println(“List after adding another list at index 2:n”+ intList);
// Removes element from index 0
intList.remove(0);
System.out.println(“List after removing element at index 0:n” + intList);
// Replace value of last element
intList.set(3, 60);
System.out.println(“List after replacing the value of last element:n” + intList);

Output:

The above program output shows the various operations performed on an ArrayList. First, it creates and initializes the list. Then it copies the contents of another list to this list and also removes an element from the list. Finally, it replaces the last element in the list with another value.

We will explore the list methods in detail in our next tutorial.

Printing List

There are various methods using which you can print the elements of the list in Java.

Lets discuss some of the methods here.

#1) Using For Loop/Enhanced For Loop

The list is an ordered collection that can be accessed using indices. You can use for loop that is used to iterate using the indices to print each element of the list.

Java has another version of for loop knows as enhanced for loop that can also be used to access and print each element of the list.

The Java program shown below demonstrates the printing of list contents using for loop and enhanced for loop.

import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
class Main
public static void main (String[] args)

//string list
List list = Arrays.asList(“Java”, “Python”, “C++”, “C”, “Ruby”);
//print list using for loop
System.out.println(“List contents using for loop:”);
for (int i = 0; i <list.size(); i++)
System.out.print(list.get(i) + " ");

//print list using enhanced for loop
System.out.println("nnList contents using enhanced for loop:");
for (String s : list)
System.out.print(s + " ");

Output:

#2) Using The toString Method

The method toString() of the list interface returns the string representation of the list.

The program below demonstrates the usage of the toString() method.

import java.util.List;
import java.util.ArrayList;
class Main
public static void main (String[] args)
//initialize a string list
List list = new ArrayList()add(“Python”);add(“C++”);add(“Java”);;
// string representation of list using toString method
System.out.println(“List contents using toString() method:” + list.toString());

Output:

List Converted To An Array

The list has a method toArray() that converts the list to an array. Once converted to an array, you can use the array methods discussed in the respective topic to print the contents of this array. You can either use for or enhanced for loop or even toString method.

The example given below uses the toString method to print the array contents.

import java.util.*;
class Main

public static void main (String[] args)

//list of odd numbers
List oddlist = Arrays.asList(1,3,5,7,9,11);
// using List.toArray() method
System.out.println(“Contents of list converted to Array:”);
System.out.println(Arrays.toString(oddlist.toArray()));

Output:

Using Java 8 Streams

Streams are introduced in Java 8. You can make use of streams to loop through the list. There are also lambdas using which you can iterate through the list.

The program below shows the usage of streams to iterate through the list and display its contents.

import java.util.*;
class Main
public static void main (String[] args)
//list of even numbers
List evenlist = Arrays.asList(2,4,6,8,10,12,14);
// print list using streams
System.out.println(“Contents of evenlist using streams:”);
evenlist.stream().forEach(S ->System.out.print(S + ” “));

Output:

Apart from the methods discussed above, you can use list iterators to iterate through the list and display its contents. We will have a complete article on the list iterator in the subsequent tutorials.

List Of Lists

Java list interface supports the list of lists. In this, the individual elements of the list is again a list. This means you can have a list inside another list.

This concept is very useful when you have to read data from say CSV files. Here, you might need to read multiple lists or lists inside lists and then store them in memory. Again you will have to process this data and write back to the file. Thus in such situations, you can maintain a list of lists to simplify data processing.

The following Java program demonstrates an example of a Java list of lists.

In this program, we have a list of lists of type String. We create two separate lists of type string and assign values to these lists. Both these lists are added to the list of lists using the add method.

To display the contents of the list of lists, we use two loops. The outer loop (foreach) iterates through the lists of lists accessing the lists. The inner foreach loop accesses the individual string elements of each of these lists.

import java.util.ArrayList;
import java.util.List;
public class Main
public static void main(String[] args)
//create list of lists
List<ArrayList> java_listOfLists = new ArrayList<ArrayList>();
//create a language list and add elements to it
ArrayList lang_list = new ArrayList();
lang_list.add(“Java”);
lang_list.add(“C++”);
//add language list to java list of list
java_listOfLists.add(lang_list);
//create a city list and add elements to it
ArrayList city_list = new ArrayList();
city_list.add(“Pune”);
city_list.add(“Mumbai”);
//add the city list to java list of lists
java_listOfLists.add(city_list);
//display the contents of list of lists
System.out.println(“Java list of lists contents:”);
java_listOfLists.forEach((list) -> //access each list

list.forEach((city)->System.out.print(city + ” “)); //each element of inner list
);

Output:

Java list of lists is a small concept but is important especially when you have to read complex data in your program.

Frequently Asked Questions

Q. #1) What is a list and set in Java?

Answer: A list is an ordered collection of elements. You can have duplicate elements in the list.

A set is not an ordered collection. Elements in the set are not arranged in any particular order. Also, the elements in the set need to be unique. It doesnt allow duplicates.

Q. #2) How does a list work in Java?

Answer: The list is an interface in Java that extends from the Collection interface. The classes ArrayList, LinkedList, Stack, and Vector implement the list interface. Thus a programmer can use these classes to use the functionality of the list interface.

Q. #3) What is an ArrayList in Java?

Answer: ArrayList is a dynamic array. It is a resizable collection of elements and implements the list interface. ArrayList internally makes use of an array to store the elements.

Q. #4) Do lists start at 0 or 1 in Java?

Answer: Lists in Java have a zero-based integer index. This means that the first element in the list is at index 0, the second element at index 1 and so on.

Q. #5) Is the list ordered?

Answer: Yes. The list is an ordered collection of elements. This order is preserved, during the insertion of a new element in the list,

Conclusion

This tutorial gave an introduction to the list interface in Java. We also discussed the major concepts of lists like creation, initialization of lists, Printing of lists, etc.

In our upcoming tutorials, we will discuss the various methods that are provided by the list interface. We will also discuss the iterator construct that is used to iterate the list object. We will discuss the conversion of list objects to other data structures in our upcoming tutorial.

=> Visit Here To See The Java Training Series For All.

  • Java Array – Declare, Create & Initialize An Array In Java
  • Array Of Objects In Java: How To Create, Initialize And Use
  • Java Hello World – Create Your First Program In Java Today
  • Java Deployment: Creation and Execution of Java JAR File
  • Java Virtual Machine: How JVM Helps in Running Java Application
  • Access Modifiers In Java – Tutorial With Examples
  • Java Reflection Tutorial With Examples
  • Introduction To Java Programming Language – Video Tutorial

Reply
0
0
Chia sẻ

Video full hướng dẫn Share Link Tải Add List ?

– Một số Keyword tìm kiếm nhiều : ” đoạn Clip hướng dẫn Add List tiên tiến và phát triển nhất , Chia Sẻ Link Download Add List “.

Giải đáp vướng mắc về Add List

Bạn trọn vẹn có thể để lại Comments nếu gặp yếu tố chưa hiểu nhé.
#Add #List