How to convert array into set
Here is simple way to convert array in to Set . The main purpose of this conversion
if you to remove the duplicate elements of the array . Here i have use simplest way conversion you can do it using for loop for
import java.util.*;
//import java.util.stream.*;
class ArrayToSet {
// Generic function to convert an Array to Set
public static <T> Set<T> convertArrayToSet(T array[])
{
// Create the Set by passing the Array
// as parameter in the constructor
Set<T> set = new HashSet<>();
// Add the array to set
Collections.addAll(set, array);
// Return the converted Set
return set;
}
public static void main(String args[])
{
// Create an Array
String array[] = { " apple ", "lenovo",
"HP" ,"HP"};
for (String element: array) {
System.out.println(element);
}
// convert the Array to Set
Set<String>
set = convertArrayToSet(array);
// Print the Set
System.out.println("Set: " + set);
}
} Here is output of the program :
apple
lenovo
HP
HP
Set: [HP, apple , lenovo]
How to convert array into set
Reviewed by Mukesh Jha
on
10:44 AM
Rating:
No comments:
Add your comment