- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java program to join two given lists in Java
The addAll() method of the java.util.ArrayList class is used to insert all of the elements in the specified collection into this list. To add contents of a list to another −
Create list1 by instantiating list objects (in this example we used ArrayList).
Add elements to it using add() method.
Create another list. Add elements to it.
Now add the elements of one list to other using the addAll() method.
Example
import java.util.ArrayList; public class JoinTwoLists { public static void main(String args[]){ ArrayList<String> list1 = new ArrayList<String>(); list1.add("Apple"); list1.add("Orange"); list1.add("Banana"); System.out.println("Contents of list1 ::"+list1); ArrayList<String> list2 = new ArrayList<String>(); list2.add("Grapes"); list2.add("Mango"); list2.add("Strawberry"); System.out.println("Contents of list2 ::"+list2); list1.addAll(list2); System.out.println("Contents of list1 after adding list2 to it ::"+list1); } }
Output
Contents of list1 ::[Apple, Orange, Banana] Contents of list2 ::[Grapes, Mango, Strawberry] Contents of list1 after adding list2 to it ::[Apple, Orange, Banana, Grapes, Mango, Strawberry]
Advertisements