Write a method that convert an array to a set in Java.
Signature
public static <T> Set<T> toSet(final T... elements)
Find the below working application.
ArrayToSet.java
package com.sample.app.collections;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class ArrayToSet {
/**
*
* @param <T>
* @param objects
*
* @return empty set if the objects is null or empty, else return a set that
* contain array elements.
*/
@SafeVarargs
public static <T> Set<T> toSet(final T... elements) {
if (elements == null || elements.length == 0) {
return Collections.emptySet();
}
return new HashSet<>(Arrays.asList(elements));
}
public static void main(String[] args) {
Integer[] primes = { 2, 3, 5, 7, 11 };
Set<Integer> primesSet = toSet(primes);
System.out.println(primesSet);
}
}
Output
[2, 3, 5, 7, 11]
You may like
Convert an enumeration to Iterable in Java
How to check the type or object is a map or not?
No comments:
Post a Comment