How to convert an Array to a Set in Java?
Answers
Answer:An array is a group of like-typed variables that are referred to by a common name. An array can contain primitives data types as well as objects of a class depending on the definition of the array. In case of primitives data types, the actual values are stored in contiguous memory locations. In case of objects of a class, the actual objects are stored in heap segment.
Set in Java is a part of java.util package and extends java.util.Collection interface. It does not allow the use of duplicate elements and at max can accommodate only one null element. Few important features of Java Set interface are as follows:
The set interface is an unordered collection of objects in which duplicate values cannot be stored.
The Java Set does not provide control over the position of insertion or deletion of elements.
Basically, Set is implemented by HashSet, LinkedHashSet or TreeSet (sorted representation).
Set has various methods to add, remove clear, size, etc to enhance the usage of this interface.
Below are methods to convert Array to Set in Java:
Brute Force or Naive Method: In this method, an empty Set is created and all elements present of the Array are added to it one by one.
Algorithm:
Get the Array to be converted.
Create an empty Set
Iterate through the items in the Array.
For each item, add it to the Set
Return the formed Set
Program:
// Java Program to convert
// Array to Set
import java.util.*;
import java.util.stream.*;
class GFG {
// Generic function to convert an Array to Set
public static <T> Set<T> convertArrayToSet(T array[])
{
// Create an empty Set
Set<T> set = new HashSet<>();
// Iterate through the array
for (T t : array) {
// Add each element into the set
set.add(t);
}
// Return the converted Set
return set;
}
public static void main(String args[])
{
// Create an Array
String array[] = { "Geeks", "forGeeks",
"A Computer Portal" };
// Print the Array
System.out.println("Array: " + Arrays.toString(array));
// convert the Array to Set
Set<String>
set = convertArrayToSet(array);
// Print the Set
System.out.println("Set: " + set);
}
}