Saturday 12 November 2022

Convert an array to set in Java

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

Interview Questions

Collection programs in Java

Array programs in Java

Convert an enumeration to Iterable in Java

How to check the type or object is a map or not?

Get a map from array in Java

Convert an iterator to set in Java

Convert an enumeration to set in Java

No comments:

Post a Comment