Programming Tips - Java: Best way to convert a Java array into a HashSet

Date: 2016jan22 Update: 2025sep18 Language: Java Q. Java: Best way to convert a Java array into a HashSet<> A. Use Arrays.asList() in the HashSet constructor. As shown in this full example:
import java.util.HashSet; import java.util.Arrays; class Demo { public static void main(String []args) { final String [] a = { "apple", "snapple", "crackle" }; HashSet<String> choices = new HashSet<String>(Arrays.asList(a)); // HERE System.out.println("choices=" + choices); } }
Output:
choices=[apple, snapple, crackle]