Java Program to Add the Data from the Specified Collection in the Current Collection
The grouping of objects in a single unit is called a collection. For example Array, Lists, Hashsets, etc. Data can be added from a specified collection in the current collection by using the addAll() method in Java. This method falls under the header file, java.util.*. The addAll() method returns a true value if the adding of the collection is successful after calling the method else it returns a false value.
We can use the addAll() method in two ways namely:
- The static method
- The instance method
Let there be 2 lists.
The static method Declaration
Collections.addAll(List1,List2)
The instance method Declaration
Let the index where List2 needs to be inserted in List1 is 1.
List1.addAll(1, List2);
The addAll() method always throws the following exceptions:
- NullPointerException: This exception is thrown if the specified or the current collection has null values.
- IllegalArgumentException: If the arguments of the specified collection have values that prevent them from being added to the current collection, this exception is thrown.
Example 1:
Input: boolean b = List1.addAll(large,extra-large)
If the appending is successful
Output: true
If the appending is unsuccessful
Output: false
Example 2:
Input: Collections.addAll(List1,List2)
Output: List1 = [small,medium,large,extra-large]
Approach used:
- Initializing the two collections.
- Using the addAll() method to append the lists.
- Checking the boolean value of the method call.
- Printing the collections’ final values.
Below is the implementation of the above approach:
Java
import java.util.*;
public class AddCollections {
public static void main(String[] args)
{
ArrayList<Integer> list = new ArrayList<Integer>();
list.add( 1 );
list.add( 2 );
list.add( 3 );
System.out.println(
"Initial collection value of list: " + list);
ArrayList<Integer> list2 = new ArrayList<Integer>();
list2.add( 4 );
list2.add( 5 );
list2.add( 6 );
System.out.println(
"Initial collection value of list2: " + list2);
boolean b = list.addAll( 2 , list2);
System.out.println( "Boolean Result: " + b);
System.out.println(
"Final collection value of list: " + list);
Integer[] arr = new Integer[ 4 ];
arr[ 0 ] = 9 ;
arr[ 1 ] = 8 ;
arr[ 2 ] = 7 ;
arr[ 3 ] = 6 ;
Collections.addAll(list2, arr);
System.out.println(
"Final collection value of list2: " + list2);
}
}
|
Output
Initial collection value of list: [1, 2, 3]
Initial collection value of list2: [4, 5, 6]
Boolean Result: true
Final collection value of list: [1, 2, 4, 5, 6, 3]
Final collection value of list2: [4, 5, 6, 9, 8, 7, 6]
Last Updated :
05 Oct, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...