Java - Convert Array to Set(HashSet)

Introduces how to convert an array to a Set(HashSet).

Conversion Using the HashSet Constructor

If you pass a List to the HashSet constructor, all elements in the list are added to the Set. Therefore, first convert the array with Arrays.asList(), and then pass it to the HashSet constructor.

package com.devkuma.basic.collection.array;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class ConvertArrayToSet1 {
    public static void main(String[] args) {
        String[] arr = { "a", "b", "c", "d" };

        Set<String> set = new HashSet<>(Arrays.asList(arr));

        System.out.println(set);
    }
}

Execution result:

[a, b, c, d]

Conversion Using the Set.addAll() Method

Convert the array to a List with Arrays.asList(), and then add all contents of the List to the Set with Set.addAll().

package com.devkuma.basic.collection.array;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class ConvertArrayToSet2 {
    public static void main(String[] args) {
        String[] arr = { "a", "b", "c", "d" };

        Set<String> set = new HashSet<>();
        set.addAll(Arrays.asList(arr));

        System.out.println(set);
    }
}

Execution result:

[a, b, c, d]