Algorithm
Convert Array to HashSet Algorithm:
-
Initialize HashSet:
- Create an empty HashSet to store elements.
-
Iterate Through Array:
- For each element in the array:
- Add the element to the HashSet using the
add()
method.
- Add the element to the HashSet using the
- For each element in the array:
Convert HashSet to Array Algorithm:
-
Initialize Array:
- Create an array with a size equal to the HashSet's size.
-
Iterate Through HashSet:
- For each element in the HashSet:
- Add the element to the corresponding index in the array.
- For each element in the HashSet:
Code Examples
#1 Code Example- Convert Array to Set
Code -
Java Programming
import java.util.*;
public class ArraySet {
public static void main(String[] args) {
String[] array = {"a", "b", "c"};
Set < String> set = new HashSet<>(Arrays.asList(array));
System.out.println("Set: " + set);
}
}
Copy The Code &
Try With Live Editor
Output
Set: [a, b, c]
#2 Code Example- Convert Array to Set using stream
Code -
Java Programming
import java.util.*;
public class ArraySet {
public static void main(String[] args) {
String[] array = {"a", "b", "c"};
Set < String> set = new HashSet<>(Arrays.stream(array).collect(Collectors.toSet()));
System.out.println("Set: " + set);
}
}
Copy The Code &
Try With Live Editor
#3 Code Example- Convert Set to Array
Code -
Java Programming
import java.util.*;
public class SetArray {
public static void main(String[] args) {
Set < String> set = new HashSet<>();
set.add("a");
set.add("b");
set.add("c");
String[] array = new String[set.size()];
set.toArray(array);
System.out.println("Array: " + Arrays.toString(array));
}
}
Copy The Code &
Try With Live Editor
Output
Array: [a, b, c]
Demonstration
Java Programing Example to Convert Array to Set (HashSet) and Vice-Versa-DevsEnv