Home >Java >javaTutorial >Add a collection to another collection using the addAll() method of the HashSet class
Use the addAll() method of the HashSet class to add a collection to another collection
HashSet is a collection class in Java. It implements the Set interface and the underlying implementation is based on a hash table. Duplicate elements are not allowed in the HashSet collection, and the elements in the collection are unordered.
In development, we often need to add elements from one collection to another collection. The HashSet class provides the addAll() method to easily implement this function.
Below we will use an example to show how to use the addAll() method of HashSet to add a collection to another collection.
First, we create two HashSet collections:
HashSet<String> set1 = new HashSet<>(); HashSet<String> set2 = new HashSet<>();
Next, we add some elements to the set1 collection:
set1.add("apple"); set1.add("banana"); set1.add("grape");
Then, we create a List collection and add it to Add some elements to it:
List<String> list = new ArrayList<>(); list.add("orange"); list.add("strawberry");
Now, we use the addAll() method of set2 to add the elements in the list collection to set2:
set2.addAll(list);
Finally, we print the elements in the set2 collection, To verify whether the addition is successful:
System.out.println(set2);
The running result is:
[orange, strawberry]
You can see that the elements in the list collection are successfully added to the set2 collection.
Summary:
The addAll() method of the HashSet class can easily add a collection to another collection. It should be noted that the addAll() method will only add unique elements. If an element is already included in the collection, it will not be added repeatedly. In addition, the parameters of the addAll() method can be any collection class that implements the Collection interface.
In actual development, we often need to merge the elements in two collections and then perform some kind of processing. This function can be easily implemented using the addAll() method of HashSet. At the same time, the characteristics of the HashSet collection are used to ensure that there will be no duplicate elements in the merged collection.
I hope that the introduction in this article can help readers master the use of the addAll() method of HashSet. In actual development, this method can be flexibly used according to specific needs to improve development efficiency.
The above is the detailed content of Add a collection to another collection using the addAll() method of the HashSet class. For more information, please follow other related articles on the PHP Chinese website!