Java Convert Array to Set

In this post, we will see how to convert an Array to Set in Java. You can use this class as SetUtils class and it's method as a utility method in your project.
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;


public class SetUtils {

    private SetUtils() {}

    /**
     * Creates a set from the array elements.
     *
     * @param array the array with the elements
     *
     * @return the set with the elements
     */
    @SafeVarargs
    public static < T > Set < T > asSet(T...array) {
        Set < T > set = null;
        if (array != null) {
            set = new HashSet < > (Arrays.asList(array));
        }
        return set;
    }
}

Related Java HashSet Source Code Examples


Comments