In this article, we will add one HashSet contents to another HashSet using addAll method of Collection interface
Adding one HashSet to another HashSet :
Method signature:
boolean addAll(Collection c);
- This method is used to add one HashSet contents to another HashSet contents
- Returns true, if this set changed as a result of the call
AddOneHashSetToAnotherHashSet.java
package in.bench.resources.java.collections; import java.util.HashSet; public class AddOneHashSetToAnotherHashSet { public static void main(String[] args) { // 1: creating HashSet object of type String HashSet<String> hset1 = new HashSet<String>(); // adding elements to HashSet object hset1.add("Sundar Pichai"); hset1.add("Satya Nadella"); hset1.add("Shiv Nadar"); hset1.add("Shantanu Narayen"); // Iterating using enhanced for-loop System.out.println("Iterating original HashSet-1\n"); for(String str : hset1) { System.out.println(str); } // 2: creating HashSet object of type String HashSet<String> hset2 = new HashSet<String>(); // adding elements to HashSet object hset2.add("Narayan Murthy"); hset2.add("Nandan Nilekeni"); hset2.add("Shibulhset SD"); boolean boolAddAll = hset1.addAll(hset2); System.out.println("\n\nWhether invoking HashSet-1 " + "changed : " + boolAddAll); // Iterating using enhanced for-loop System.out.println("\n\nIterating after addAll operation\n"); for(String str : hset1) { System.out.println(str); } } }
Output:
Iterating original HashSet-1 Shantanu Narayen Shiv Nadar Sundar Pichai Satya Nadella Whether invoking HashSet-1 changed : true Iterating after addAll operation Shantanu Narayen Shiv Nadar Sundar Pichai Nandan Nilekeni Shibulhset SD Satya Nadella Narayan Murthy
From above example, HashSet
- doesn’t allow duplicate elements
- maximum of one null object is allowed
- while iterating, retrieve elements in random-order
References:
- https://docs.oracle.com/javase/tutorial/collections/intro/
- https://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html
- https://docs.oracle.com/javase/tutorial/collections/interfaces/set.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Set.html
- https://docs.oracle.com/javase/7/docs/api/java/util/class-use/HashSet.html
- https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html
- https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
Happy Coding !!
Happy Learning !!