Initialize set

This example will show how to initialize a set using core java and guava techniques.

Straight up Java

This snippet will show a standard way to initialize a empty HashSet with JDK 5.0 and above.

@Test
public void create_new_set_java () {
    
    Set<String> newSet = new HashSet<String>();
    
    assertNotNull(newSet);
}

Diamond operator

Java 7 introduced the diamond operator which reduces java's verbosity on having to specify generic types. The compiler will infer the parameter type based on the constructor's generic class. The snippet below will show how to initialize a HashSet using the diamond operator.

@Test
public void create_new_set_java_diamond_operator () {
    
    Set<String> newSet = new HashSet<>();
    
    assertNotNull(newSet);
}

Google Guava

Guava Sets.newHashSet will create an empty Hashset. There is also an overloaded method that will initialize and set values if required.

@Test
public void create_new_set_guava () {

    Set<String> newSet = Sets.newHashSet();
    
    assertNotNull(newSet);
}

Apache Commons

If you are looking to initialize an empty set this is an approach to take when using apache commons.

@Test
public void create_new_set_apache () {

    @SuppressWarnings("unchecked")
    Set<String> newSet = SetUtils.EMPTY_SET;
    
    assertNotNull(newSet);
}