Convert array to set in java

In this example we will show how to convert an array to a set in java and using guava. In both snippets we will use Arrays.asList, a method that acts as a bridge between an array and collection, which will return a list.

Straight up Java

Using straight up java we will initialize a HashSet by passing a collection that is returned by Arrays.asList.

@Test
public void convert_array_to_set_java() {

    String[] abcs = { "a", "b", "c", "d" };

    Set<String> abcSet = new HashSet<>(Arrays.asList(abcs));

    assertTrue(abcSet.size() == 4);
}

Google Guava

@Test
public void convert_array_to_set_guava() {

    String[] abcs = { "a", "b", "c", "d" };

    Set<String> abcSet = Sets.newConcurrentHashSet(Arrays.asList(abcs));

    assertTrue(abcSet.size() == 4);
}