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
- Creating a HashSet and Adding New Elements to It
- Java 8 forEach() Set Example
- Java Convert Array to Set
- Iterating over a HashSet using Iterator
- Iterate over HashSet in Java
- Remove Element from HashSet in Java
- Create HashSet in Java
Free Spring Boot Tutorial - 5 Hours Full Course
Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course