- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Add all the elements from a collection to the HashSet in Java
First, set the collection −
String strArr[] = { "P", "Q", "R", "S" };
Now, take a Set and add all the elements of the above collection using asList() method −
Set s = new HashSet(Arrays.asList(strArr));
The following is an example to add all elements from a collection to the HashSet −
Example
import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class Demo { public static void main(String[] a) { String strArr[] = { "P", "Q", "R", "S" }; Set s = new HashSet(Arrays.asList(strArr)); strArr = new String[] { "R", "S", "T", "U" }; s.addAll(Arrays.asList(strArr)); strArr = new String[] { "S", "T", "U" }; s.addAll(Arrays.asList(strArr)); System.out.println(s); } }
Output
[P, Q, R, S, T, U]
- Related Articles
- Remove all elements in a collection from a HashSet in C#
- Remove all elements from a HashSet in Java
- Add elements to HashSet in Java
- Remove all elements from a HashSet in C#
- Add elements to LinkedHashMap collection in Java
- How to remove all elements from a Collection in another Collection
- Remove all elements from the Collection in C#
- Check if a Java HashSet Collection contains another Collection
- Remove all the elements from an ArrayList that are in another Collection in Java
- Copy all elements of Java HashSet to an Object Array
- Check if HashSet and the specified collection contain the same elements in C#
- Append all elements of another Collection to a Vector in Java
- Create HashSet from another collection in C#
- Count the number of elements in a HashSet in Java
- Append all elements of other Collection to ArrayList in Java

Advertisements