Set in Java is an interface which extends Collection. It is an unordered collection of objects in which duplicate values cannot be stored.
Basically, set is implemented by HashSet, LinkedHashSet or TreeSet (sorted representation).
Set has various methods to add, remove clear, size, etc to enhance the usage of this interface.
Method 1: Using Constructor:
In this method first we create an array then convert it to a list and then pass it to the HashSet constructor that accepts another collection.
Integer elements of the set are printed in sorted order.
Method 2 using Collections:
Collections class consists of several methods that operate on collections.
a) Collection.addAll() : adds all the specified elements to the specified collection of the specified type.
b) Collections.unmodifiableSet() : adds the elements and returns an unmodifiable view of the specified set.
Method 3: using .add() each time
Create a set and using .add() method we add the elements into the set
[1, 2, 3, 4, 5, 6, 7, 8]
This article is contributed by Nikita Tiwari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
- Initializing a List in Java
- HashSet in Java
- Internal working of Set/HashSet in Java
- HashSet contains() Method in Java
- HashSet clear() Method in Java
- HashSet isEmpty() Method in Java
- HashSet iterator() Method in Java
- HashSet remove() Method in Java
- HashSet size() Method in Java
- HashSet add() Method in Java
- HashSet clone() Method in Java
- Traverse through a HashSet in Java
- HashSet spliterator() method in Java
- HashSet vs TreeSet in Java
- How to sort HashSet in Java
- Difference between ArrayList and HashSet in Java
- HashSet hashCode() method in Java with Example
- HashSet containsAll() method in Java with Example
- HashSet toString() method in Java with Example
- HashSet removeAll() method in Java with Example