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 email@example.com. 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.
- Initializing a List in Java
- HashSet in Java
- HashSet add() Method in Java
- Traverse through a HashSet in Java
- How to sort HashSet in Java
- HashSet vs TreeSet in Java
- HashSet contains() Method in Java
- Convert HashSet to TreeSet in Java
- HashSet spliterator() method in Java
- HashSet retainAll() method in Java with Example
- HashSet equals() method in Java with Example
- HashSet toArray(T) method in Java with Example
- HashSet toArray() method in Java with Example
- HashSet removeAll() method in Java with Example
- Internal working of Set/HashSet in Java