The Answer by Elliott Frisch is correct for modifiable sets.
Unmodifiable sets
You asked:
is it possible to declare the set with its values within the HashSet(); line?
Yes.
For unmodifiable sets in Java 9+, use Set.of
.
Set< Integer > integers = Set.of( 4 , 7 , 12 ) ;
You asked:
how can I add multiple values at once
You can use Set.of
as convenient syntax for adding to an existing set. Call Set#addAll
.
Set< Integer > integers = new HashSet<>() ;
integers.addAll( Set.of( 4 , 7 , 12 ) ) ;
That use of Set.of( 4 , 7 , 12 )
is a modern alternative to Arrays.asList( 4 , 7 , 12 )
seen in other Answers on this page.
When you are done modifying a set, you may wish to convert it into an unmodifiable set. For example, this approach is usually wise when handing off a set between methods. In Java 10+, call Set#copyOf
.
Set< Integer > integersUnmodifiable = Set.copyOf( integers ) ;
See similar code run live at IdeOne.com.