Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How do you add two lists in Java?
The addAll() method of the List interface can be used to combine two lists in Java. It comes in two variants − one appends elements at the end, and another inserts elements at a specific index.
addAll() Without Index
Appends all elements from the specified collection to the end of the list −
boolean addAll(Collection<? extends E> c)
Returns true if the list changed as a result of the call.
addAll() With Index
Inserts all elements from the specified collection at the specified position, shifting existing elements to the right −
boolean addAll(int index, Collection<? extends E> c)
The index parameter specifies the position at which the first element from the collection will be inserted.
Example
The following example demonstrates both variants of addAll() ?
import java.util.ArrayList;
import java.util.List;
public class CollectionsDemo {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
System.out.println("List: " + list);
List<String> list1 = new ArrayList<>();
list1.add("D");
list1.add("E");
list1.add("F");
System.out.println("List1: " + list1);
// addAll() without index - appends at end
list.addAll(list1);
System.out.println("After addAll(): " + list);
List<String> list2 = new ArrayList<>();
list2.add("G");
list2.add("H");
list2.add("I");
// addAll() with index - inserts at position 0
list2.addAll(0, list);
System.out.println("List2 after addAll(0, list): " + list2);
}
}
The output of the above code is ?
List: [A, B, C] List1: [D, E, F] After addAll(): [A, B, C, D, E, F] List2 after addAll(0, list): [A, B, C, D, E, F, G, H, I]
Conclusion
Use addAll(collection) to append one list to the end of another, or addAll(index, collection) to insert a list at a specific position. Both methods modify the original list and return true if elements were added successfully.
