In this tutorial we will learn about java Hashset addall() method . Hashset.addAll() method used to adds all of the elements in the given collection to this HashSet . 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 HashSet.
Return Value: Its returns true if it successfully added the elements of the collection C to this HashSet otherwise it returns False.
Example 1 : Java Hashset addall() Method Append TreeSet
In this example , Hashset.addAll() method added element of TreeSet to HashSet . We will create HashSet and TreeSet . Then we append element of TreeSet to HashSet Using addAll() method of HashSet.
import java.util.HashSet;
import java.util.TreeSet;
public class Hashsetaddall {
public static void main(String[] args) {
HashSet<String> hashSet = new HashSet<String>();
hashSet.add("Java");
hashSet.add("Vogue");
hashSet.add("Welcomes");
// print hashset
System.out.println("hashSet elements : " + hashSet);
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 hashset collection
*/
hashSet.addAll(treeSet);
System.out.println("After addAll() hashSet elements : "+hashSet);
}
}
Output:
hashSet elements : [Java, Vogue, Welcomes]
treeSet elements : [Thanks, You]
After addAll() hashSet elements : [Java, Vogue, Thanks, You, Welcomes]
Example 2 : Java Hashset addall() Method Append ArrayList
Now we add element of ArrayList to HashSet . We create HashSet and ArrayList of String . We will append element of ArrayList to HashSet using HashSet addAll method.
import java.util.ArrayList;
import java.util.HashSet;
import java.util.TreeSet;
public class Hashsetaddall1 {
public static void main(String[] args) {
HashSet<String> hashSet = new HashSet<String>();
hashSet.add("Java");
hashSet.add("Vogue");
hashSet.add("Welcomes");
// print hashset
System.out.println("hashSet elements : " + hashSet);
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("You");
arrayList.add("Thanks");
// print treeSet
System.out.println("arrayList elements : " + arrayList);
/*
* Adds all of the elements in the specified
* collection to hashset collection
*/
hashSet.addAll(arrayList);
System.out.println("After addAll() hashSet elements : "+hashSet);
}
}
Output:
hashSet elements : [Java, Vogue, Welcomes]
arrayList elements : [You, Thanks]
After addAll() hashSet elements : [Java, Vogue, Thanks, You, Welcomes]
In this tutorial we have learned java Hashset addall () method . We have added element of collection to HashSet using addAll() . you can lean more java HashSet example for practice .