
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Join Two Given Lists in Java
To join two given lists 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 ?
Problem Statement
Write a program in Java to join two given lists ?
Input
Contents of list1 ::[Apple, Orange, Banana] Contents of list2 ::[Grapes, Mango, Strawberry]
Output
Contents of list1 after adding list2 to it ::[Apple, Orange, Banana, Grapes, Mango, Strawberry]
Steps to join two given lists
Following are the steps to join two given lists ?
-
Create list1 by instantiating list objects (in this example we used ArrayList).
-
Add elements to it using the add() method.
-
Create another list and add elements to it.
-
Now add the elements of one list to another using the addAll() method.
Java program to join two given lists
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]
Code Explanation
Initialize by importing the ArrayList class from java.util package we will create two ArrayList objects that are list1 and list2 and add the elements in the list using the add() method and join both the lists together addAll() as method list1.addAll(list2) and print the result on the console.