How to Initialize a HashSet Inline in Java

Examples covering different ways of initializing Java HashSet instances and creating mutable or immutable HashSets inline.

Learn more on Java HashSets here: Introduction to Java HashSets With Examples and Introduction to Java Collections Set Interface.

Creating a Simple Java HashSet

The traditional way of creating a Java HashSet instance is to create an empty HashSet instance before adding elements to it.
Example of initializing a Java HashSet traditionally.

Set<String> shoppingSet = new HashSet<>();

shoppingSet.add("Bread");
shoppingSet.add("Milk");
shoppingSet.add("Eggs");
shoppingSet.add("Cheese");
shoppingSet.add("Butter");Code language: Java (java)

This HashSet is dynamic and mutable; thus, we can add or remove elements.

Creating a HashSet using a Collection

Alternatively, we can use an existing collection, a java List, for example, to create a Java HashSet containing the elements from the given collection.

Example of creating a Java HashSet from another collection

List<String> shoppingList = 
    List.of("Bread", "Milk", "Eggs", "Cheese", "Butter");
Set<String> shoppingSet = new HashSet<>(shoppingList);Code language: Java (java)

Here is another example of creating a Java HashSet containing all keys of an existing HashMap.

Map<String, String> map = Map.of(
    "color", "black",
    "drink", "coffee",
    "shape", "slim"
);
Set<String> set = new HashSet<>(map.keySet());
set.foreach(System.out::println);
//prints
//color
//drink
//shapeCode language: Java (java)

Creating a HashSet using Java Stream Collectors

Java Collectors interface provides many useful collector abstractions that we can use in a Stream pipeline to collect the Stream elements. The Collectors toSet() method returns a new HashSet containing all Stream elements.

Create HashSet using Java Stream Collectors.toSet().

Set<String> shoppingSet = Stream
    .of("Bread", "Milk", "Eggs", "Cheese", "Butter")
    .collect(Collectors.toSet());Code language: Java (java)

Alternatively, the toCollection() method of the Collectors collects all Stream elements into the given HashSet and returns it.
Example of Creating a Java HashSet using Collectors.toCollection() method.

Set<String> shoppingSet = Stream
    .of("Bread", "Milk", "Eggs", "Cheese", "Butter")
    .collect(Collectors.toCollection(HashSet::new));Code language: Java (java)

The argument to the toCollection() method is a Java HashSet constructor reference.

Creating a HashSet using an Anonymous Subclass

Example of creating and initializing a Java HashSet inline using Anonymous Subclass.

Set<String> shoppingSet = new HashSet<>() {
    {
        add("Bread");
        add("Milk");
        add("Eggs");
        add("Cheese");
        add("Butter");
    }
};Code language: Java (java)

Although this method looks short and simple, it is expensive. Because it creates an anonymous subclass and an extra initialization block, it gets executed every time it is used. Moreover, there are possibilities of memory leak issues.

Creating an Immutable HashSet using a Collection

Immutable HashSet using Collections.unmodifiableSet.

Set<String> shoppingSet = 
    new HashSet<>(List.of("Bread", "Milk", "Eggs", "Cheese", "Butter"));

Set<String> immutableSet = 
    Collections.unmodifiableSet(shoppingSet);Code language: Java (java)

Using the Collections unmodifiableSet() method, we can create an immutable HashSet containing all the elements from the given collection.

Creating a Singleton HashSet

The singleton() method of the Collections creates an immutable HashSet containing the given element. A singleton HashSet always contains one and only one element, and given that it is immutable, we cannot modify the element.

Set<String> singletonSet = Collections.singleton("Bread");Code language: Java (java)

Creating a HashSet using Guava

The Guava library provides many useful abstractions and utility methods to work with Java Collections. It offers a few ways to create mutable and immutable Java HashSet instances.

Immutable HashSet using Guava

The ImmutableSet class of the Guava library provides a factory method to create an immutable instance of Java HashSet inline.
Immutable HashSet using Google Guava Library.

Set<String> shoppingSet = ImmutableSet.of("Bread", "Milk", "Eggs", "Cheese", "Butter");Code language: Java (java)

Mutable HashSet using Guava

Alternatively, the Sets class of the library provides the newHashSet() method, a factory method, which initializes a mutable Java HashSet inline.
Mutable HashSet using Google Guava Library.

Set<String> shoppingSet = Sets.newHashSet ("Bread", "Milk", "Eggs", "Cheese", "Butter");Code language: Java (java)

As this is a mutable HashSet, we can remove or add more elements.

Creating HashSet inline in Plain Java

Since Java 9, the Set interface supports various useful methods. For this example, we will look at the of() method, a factory method, for creating HashSets.

Set<String> shoppingSet = 
    Set.of("Bread", "Milk", "Eggs", "Cheese", "Butter");Code language: Java (java)

The Set instances we create using the Java Set factory method are immutable.

Summary

This tutorial demonstrated different ways of creating and initializing mutable and immutable versions of Java HashSet instances inline.

Java 9 introduced a factory method in the Set interface that is the most compact and straightforward way to create an immutable instance of Java HashSet inline. However, there are other ways available too.

Please refer to our GitHub Repository for the complete source code of this tutorial.