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?
If we’re on Java 8+, we can use
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));
More Java Articles
- How to Convert a Map to List in Java
- How to Get All Keys From Map With a Value in Java
- How to Remove the Last Character in a String in Java
- How to Remove the First Character in a String in Java
- How to Split a String Over Only the First Occurrence in Java
- How to Get the Substring Before a Character in Java
- How to Pass Dynamic Number of Parameters in Java
- How to Use Generics with Abstract Classes in Java For Different Parameter Types
- How to Replace the String Between Two Characters in Java
- How to Print Elements of a List in Java Without Loops
- How to Ignore Test Cases in JUnit
- How to Add Multiple Elements to List At Once in Java