How to Add Multiple Elements to a HashSet At Once in Java


How can we add multiple values to a HashSet all at once in Java?

Stream.of()

If we’re on Java 8+, we can use Stream.of().

From the docs:

Stream.of() returns a sequential ordered stream whose elements are the specified values.

So, we can declare a stream with our values, and collect it as a set.

Set<Integer> set = Stream.of(1,2,3).collect(Collectors.toSet());

Arrays.asList()

We can also pass a list into the HashSet constructor to insert values simultaneously.

Set<Integer> set = new HashSet<Integer>(Arrays.asList(1,2,3));