How to convert an array to Set in Java?

If you’re just getting started and want a simple way to convert a java array to set, using HashSet with Arrays.asList() is a straightforward option.

import java.util.*;

public class Main {
    public static void main(String[] args) {
        String[] array = {"apple", "banana", "orange", "apple"};  
        Set<String> set = new HashSet<>(Arrays.asList(array));  

        System.out.println(set); // Output: [banana, orange, apple]
    }
}

:white_check_mark: Why this works:

Arrays.asList()creates aListfrom the array, and wrapping it in aHashSetensures uniqueness. This is a quick and easy way to convert ajava array to set`.