JavaTechnology

How to Initialize a HashSet Inline in Java

A quick guide to Create and Initialize a HashSet at the time of Construction in Java. This is also called as Creating HashSets inline.

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

Create Mutable HashSets Normal Way

Before we jump on to create HashSets inline, we will see how to create them in a normal way. In other words, lets first create an Empty HashSet and then add elements to it.

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

shoppingSet.add("Bread");
shoppingSet.add("Milk");
shoppingSet.add("Eggs");
shoppingSet.add("Cheese");
shoppingSet.add("Butter");

When we print it:

shoppingSet.forEach(System.out::println);

// Output
//Butter
//Cheese
//Eggs
//Bread
//Milk

This HashSet is mutable and dynamic. Therefore, you can add as many elements as and when you want.

Create HashSet using a Collection

Alternatively, you can also create a HashSet using another HashSet or a different collection like List.

Create HashSet from a List

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

Create HashSet from any Collection. For example, we will create a HashSet of all the keys from a HashMap.

Map<String, String> map = new HashMap<>();
map.put("color", "black");
map.put("drink", "coffee");
map.put("shape", "slim");
Set<String> set = new HashSet<>(map.keySet());

When we print:

set.forEach(System.out::println);

// Output
// color
// shape
// drink

Create HashSet using Java 8 Stream Collectors

The Java 8 Streams Collectors also support sets. You can have a Stream of any collection and convert it to a HashSet.

Create HashSet using Java Stream Collectors.toSet()

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

Create HashSet using Java Stream Collectors.toCollection()

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

Using Anonymous Subclass to Create HashSet

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

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

Immutable HashSet using Java Collections

Immutable HashSet using Collections.unmodifiableSet.

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

Set<String> immutableSet = 
        Collections.unmodifiableSet(shoppingSet);

You can use any previously created HashSet and create a totally separate immutable set. However, once created, you cannot modify the elements of an immutable HashSet.

Create Singleton HashSet

Set<String> singletonSet = Collections.singleton("Bread");

This is a traditional way of creating Singleton Set using Java Collections. However, A singleton set is implicitly immutable. Hence, you cannot add more element or modify the existing element of a Singleton HashSet.

Mutable and Immutable HashSet Using Guava

Immutable HashSet using Google Guava Library.

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

Mutable HashSet using Google Guava Library.

Set<String> shoppingSet = Sets.newHashSet ("Bread", "Milk", "Eggs", "Cheese", "Butter");

As this is a mutable HashSet, you can remove or add more elements to it.

HashSet Using Java 9 Set Interface

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

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

However, the Set you create out of this is Immutable. Hence you cannot change or add any elements to it.

Summary

Finally, we are at the end of the this short tutorial. You learnt how to Create Mutable Sets, Immutable Sets, and Singleton Sets using various ways. Also you learnt How to Create HashSets inline in Java.


Leave a Reply

Your email address will not be published. Required fields are marked *