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

Published Sep 26, 2021  ∙  Updated May 9, 2022

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


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());


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));