Java Set addAll() Method With Examples

In this tutorial We will discuss about java set addall() method. java.util.Set.addAll(Collection C) method used to adds all of the elements in the given collection C to this Set . The elements are added without following any specific order.

Syntax :

boolean addAll(Collection C)

Parameters: Given parameter C is a collection of any type in java that is to be added to the Set.

Return Value: Its returns true if it successfully added the elements of the collection C to this Set otherwise it returns False.

Now we will discuss java.util.Set.addAll() method with examples below .

Example 1 : Java Set addall() Method Example – Append TreeSet

In this example , Set.addAll() method added element of TreeSet to Set . We will we append element of TreeSet to Set Using addAll() method of Set.

import java.util.Set;
import java.util.TreeSet;

public class SetAddall {

	public static void main(String[] args) {

		Set<String> Set = new TreeSet<String>();
		Set.add("Java");
		Set.add("Vogue");
		Set.add("Welcomes");

		// print Set Elements 
		System.out.println("Set Elements : " + Set);

		TreeSet<String> treeSet = new TreeSet<String>();

		treeSet.add("You");
		treeSet.add("Thanks");

		// print treeSet
		System.out.println("TreeSet elements : " + treeSet);

		/*
		 * Adds all of the elements in the specified collection to Set
		 * collection
		 */

		Set.addAll(treeSet);

		System.out.println("After addAll() Set elements : " + Set);

	}

}

Output:

Set Elements : [Java, Vogue, Welcomes]
TreeSet elements : [Thanks, You]
After addAll() Set elements : [Java, Thanks, Vogue, Welcomes, You]

Example 2 : Java Set addall() Method Example – Add List to Set

Now we will add List to Set in java. We create Set and ArrayList of String . We will append element of ArrayList to Set using Set.addAll() method.
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

public class SetAddall1 {

	public static void main(String[] args) {
		Set<String> Set = new TreeSet<String>();
		Set.add("Java");
		Set.add("Vogue");
		Set.add("Welcomes");

		// print Set Elements
		System.out.println("Set elements : " + Set);

		List<String> list = new ArrayList<String>();

		list.add("You");
		list.add("Thanks");

		// print list element
		System.out.println("List elements : " + list);

		/*
		 * Adds all of the elements in the specified collection to Set
		 * collection
		 */

		Set.addAll(list);

		System.out.println("After addAll() Set elements : " + Set);

	}

}
Output:
Set elements : [Java, Vogue, Welcomes]
List elements : [You, Thanks]
After addAll() Set elements : [Java, Thanks, Vogue, Welcomes, You]
In this tutorial we learned about java Set addAll() method . you can learn more java TreeSet example for practice .
Reference:

Leave a Reply

Your email address will not be published. Required fields are marked *

+ 37 = 47