Converting an Array to HashSet in Java can be achieved by utilizing the HashSet constructor that takes a Collection as a parameter.
Here's a step-by-step example tutorial on how to convert an Array to HashSet in Java:
Step 1: Import the required classes.
import java.util.Arrays;
import java.util.HashSet;
Step 2: Declare and initialize an array with elements.
String[] array = {"apple", "banana", "orange", "kiwi", "banana"};
Step 3: Create a HashSet object and pass the array as a parameter to its constructor.
HashSet set = new HashSet<>(Arrays.asList(array));
Step 4: Now, the array elements have been converted to a HashSet.
You can perform various operations on the set, such as adding or removing elements, checking for containment, or iterating through the elements. Here's a complete example demonstrating the conversion of an array to a HashSet and performing some operations:
import java.util.Arrays;
import java.util.HashSet;
public class ArrayToHashSetExample {
public static void main(String[] args) {
String[] array = {"apple", "banana", "orange", "kiwi", "banana"};
HashSet set = new HashSet<>(Arrays.asList(array));
// Print the HashSet
System.out.println("HashSet: " + set);
// Add a new element to the HashSet
set.add("grape");
System.out.println("HashSet after adding 'grape': " + set);
// Remove an element from the HashSet
set.remove("banana");
System.out.println("HashSet after removing 'banana': " + set);
// Check if an element exists in the HashSet
boolean containsKiwi = set.contains("kiwi");
System.out.println("Does the HashSet contain 'kiwi'? " + containsKiwi);
// Iterate through the HashSet
System.out.println("Iterating through the HashSet:");
for (String element : set) {
System.out.println(element);
}
}
}
OUTPUT :
HashSet: [orange, kiwi, apple, banana]
HashSet after adding 'grape': [orange, kiwi, apple, grape, banana]
HashSet after removing 'banana': [orange, kiwi, apple, grape]
Does the HashSet contain 'kiwi'? true
Iterating through the HashSet:
orange
kiwi
apple
grape
In this example, the array is converted to a HashSet using the HashSet constructor that takes a Collection as a parameter. The resulting HashSet can be used to perform various operations efficiently, such as adding or removing elements, checking for containment, or iterating through the elements.
No comments:
Post a Comment