How to initialize HashSet values by construction?
Categories:
Initializing HashSet Values by Construction in Java

Learn various effective methods to initialize a HashSet
with values directly during its construction in Java, enhancing code readability and efficiency.
Initializing a HashSet
with pre-defined values at the time of its creation is a common requirement in Java programming. While HashSet
doesn't provide a direct constructor that accepts a variable number of elements, there are several idiomatic and efficient ways to achieve this. This article explores different techniques, from using utility classes to more modern Java features, helping you choose the best approach for your specific needs.
Understanding HashSet Initialization Challenges
The HashSet
class in Java's java.util
package is designed for storing unique elements without any specific order. Its primary constructors are HashSet()
for an empty set and HashSet(Collection<? extends E> c)
for initializing with elements from an existing collection. The challenge arises when you want to populate it with a few specific elements directly at the point of declaration, rather than adding them one by one after creation.
flowchart TD A[Start] B{Need to initialize HashSet with values?} C[Use Arrays.asList() + new HashSet()] D[Use anonymous inner class (double brace initialization)] E[Use Stream API (Java 8+)] F[Use Set.of() (Java 9+)] G[End] A --> B B -->|Yes| C B -->|Yes| D B -->|Yes| E B -->|Yes| F C --> G D --> G E --> G F --> G
Decision flow for HashSet initialization methods
Method 1: Using Arrays.asList()
with HashSet
Constructor
This is one of the most common and straightforward ways to initialize a HashSet
with a fixed set of values. You first create a List
using Arrays.asList()
and then pass this List
to the HashSet
constructor. This method is widely compatible across Java versions.
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class HashSetInit {
public static void main(String[] args) {
Set<String> fruits = new HashSet<>(Arrays.asList("Apple", "Banana", "Orange"));
System.out.println("Fruits: " + fruits);
Set<Integer> numbers = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5));
System.out.println("Numbers: " + numbers);
}
}
Initializing HashSet using Arrays.asList()
List
returned by Arrays.asList()
is a fixed-size list. While you can add its elements to a HashSet
, you cannot add or remove elements directly from the List
itself. This is generally not an issue when its sole purpose is to initialize another collection.Method 2: Double Brace Initialization (Anonymous Inner Class)
Double brace initialization is a concise, though sometimes controversial, technique. It involves creating an anonymous inner class that extends HashSet
and then using an instance initializer block to add elements. The first brace creates the anonymous inner class, and the second brace defines the instance initializer block.
import java.util.HashSet;
import java.util.Set;
public class DoubleBraceInit {
public static void main(String[] args) {
Set<String> colors = new HashSet<String>() {{
add("Red");
add("Green");
add("Blue");
}};
System.out.println("Colors: " + colors);
}
}
Initializing HashSet using double brace initialization
Method 3: Using Java 8 Stream API
For Java 8 and later, the Stream API offers a functional approach to initialize collections. You can create a stream of elements and then collect them into a HashSet
using Collectors.toSet()
.
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamInit {
public static void main(String[] args) {
Set<String> animals = Stream.of("Dog", "Cat", "Bird", "Fish")
.collect(Collectors.toCollection(HashSet::new));
System.out.println("Animals: " + animals);
// Alternatively, if you don't need a specific Set implementation:
Set<String> vehicles = Stream.of("Car", "Bike", "Truck")
.collect(Collectors.toSet());
System.out.println("Vehicles: " + vehicles);
}
}
Initializing HashSet using Java 8 Stream API
Collectors.toCollection(HashSet::new)
guarantees a HashSet
instance. If you use Collectors.toSet()
, the specific Set
implementation returned is not guaranteed (it could be a HashSet
, LinkedHashSet
, etc.), though it's typically a HashSet
for small sets.Method 4: Using Set.of()
(Java 9+)
Java 9 introduced convenient factory methods like Set.of()
for creating immutable sets. This is the most concise and recommended way to create a small, immutable Set
with initial values. If you need a mutable HashSet
, you can then pass this immutable Set
to the HashSet
constructor.
import java.util.HashSet;
import java.util.Set;
public class SetOfInit {
public static void main(String[] args) {
// Create an immutable Set directly
Set<String> immutablePlanets = Set.of("Mars", "Earth", "Jupiter");
System.out.println("Immutable Planets: " + immutablePlanets);
// Create a mutable HashSet from an immutable Set
Set<String> mutablePlanets = new HashSet<>(Set.of("Mars", "Earth", "Jupiter"));
mutablePlanets.add("Saturn");
System.out.println("Mutable Planets: " + mutablePlanets);
}
}
Initializing HashSet using Java 9+ Set.of()
Set.of()
method creates an immutable set. Any attempt to modify it (add, remove) will result in an UnsupportedOperationException
. If mutability is required, wrap it in a new HashSet<>()
constructor as shown in the example.