Algorithm


Convert Array to HashSet Algorithm:

  1. Initialize HashSet:

    • Create an empty HashSet to store elements.
  2. Iterate Through Array:

    • For each element in the array:
      • Add the element to the HashSet using the add() method.

Convert HashSet to Array Algorithm:

  1. Initialize Array:

    • Create an array with a size equal to the HashSet's size.
  2. Iterate Through HashSet:

    • For each element in the HashSet:
      • Add the element to the corresponding index in the array.

 

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

x
+
cmd
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

x
+
cmd
Array: [a, b, c]
Advertisements

Demonstration


Java Programing Example to Convert Array to Set (HashSet) and Vice-Versa-DevsEnv