You can create a new HashSet in Java by using the new operator and then initialize it by using add or addAll method. Apart from that, you can also initialize from another collection when creating a new HashSet

Let's walk through this tutorial to explore them in more details

Initialize by using add method

  • Create and initialize a HashSet in multiple lines
@Test
public void initializeInMultipleLines() {  
    // Create a new HashSet
    Set<Integer> set = new HashSet<>();

    // Add elements to HashSet
    set.add(3);
    set.add(1);
    set.add(2);

    // Can add null element
    set.add(null);

    // Duplicate element will be ignored
    set.add(2);
    assertThat(set).hasSize(4);

    // The output ordering will be vary as Set is not reserved the insertion order
    System.out.println(set);
}
  • Create and initialize a HashSet in one line with double brace
@Test
public void initializeInOneLine() {  
    // Create a new HashSet
    Set<Integer> set = new HashSet<>(){{
        add(3);
        add(1);
        add(2);
    }};
    assertThat(set).hasSize(3);

    // The output ordering will be vary as Set is not reserved the insertion order
    System.out.println(set);
}

Double brace initialization can lead to memory leaks as it creates an anonymous class with a reference to the owner object, so we should not use it in practice

Initialize from another collection

You can initialize a HashSet from an existing collection or with Arrays.asList, Java 9+ List.of and Set.of

  • Initialize from another collection by using addAll method
@Test
public void initializeByAddAll() {  
    // Create a new HashSet
    Set<Integer> set1 = new HashSet<>();

    // Add all from Java 9+ List.of
    set1.addAll(List.of(3, 1, 2));

    // Add all from Arrays.asList
    set1.addAll(Arrays.asList(5, 4, 6));

    // Add all from Java 9+ Set.of
    set1.addAll(Set.of(8, 7, 9));

    assertThat(set1).hasSize(9);

    // Add all from an existing collection
    Set<Integer> set2 = new HashSet<>();
    set2.addAll(set1);
    assertThat(set2).hasSize(9);
}
  • Initialize from another collection when creating a new HashSet
@Test
public void initializeFromAnotherCollectionWhenCreating() {  
    // create and initialize a HashSet from Java 9+ List.of
    Set<Integer> set1 = new HashSet<>(List.of(3, 1, 2));
    assertThat(set1).hasSize(3);

    // create and initialize a HashSet from Arrays.asList
    Set<Integer> set2 = new HashSet<>(Arrays.asList(3, 1, 2));
    assertThat(set2).hasSize(3);

    // create and initialize a HashSet from Java 9+ Set.of
    Set<Integer> set3 = new HashSet<>(Set.of(5, 4, 6));
    assertThat(set3).hasSize(3);

    // create and initialize from an existing collection
    Set<Integer> set4 = new HashSet<>(set3);
    assertThat(set4).hasSize(3);
}

Conclusion

In this tutorial, we learned some ways to create and initialize a HashSet in Java. You can find the full source code as below