Sunday, December 29, 2024
Google search engine
HomeData Modelling & AIProgram to convert Array to Set in Java

Program to convert Array to Set in Java

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 the 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 the 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.

Examples:

Input: Array: [Geeks, forGeeks, A computer Portal] 
Output: Set: [Geeks, forGeeks, A computer Portal] 

Input: Array: [1, 2, 3, 4, 5] 
Output: Set: [1, 2, 3, 4, 5]

Below are methods to convert Array to Set in Java:

Method 1: 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:

  1. Get the Array to be converted.
  2. Create an empty Set
  3. Iterate through the items in the Array.
  4. For each item, add it to the Set
  5. Return the formed Set

Example:

Java




// 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);
    }
}


Output

Array: [Geeks, forGeeks, A Computer Portal]
Set: [A Computer Portal, Geeks, forGeeks]

Way 2: Using Arrays.asList() method: In this method, the Array is passed as the parameter into the Set constructor in the form of an Array with the help of Arrays.asList() method.

Algorithm:

  1. Get the Array to be converted.
  2. Create the Set by passing the Array as parameter in the constructor of the Set with the help of Arrays.asList() method
  3. Return the formed Set

Example

Java




// 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 the Set by passing the Array
        // as parameter in the constructor
        Set<T> set = new HashSet<>(Arrays.asList(array));
  
        // 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);
    }
}


Output

Array: [Geeks, forGeeks, A computer Portal]
Set: [A computer Portal, Geeks, forGeeks]

Way 3: Using Collections.addAll(): Since Set is a part of the Collection package in Java. Therefore the Array can be converted into the Set with the help of Collections.addAll() method. 

Algorithm:

  1. Get the Array to be converted.
  2. Create an empty Set.
  3. Add the array into the Set by passing it as the parameter to the Collections.addAll() method.
  4. Return the formed Set

Java




// 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 the Set by passing the Array
        // as parameter in the constructor
        Set<T> set = new HashSet<>();
  
        // Add the array to set
        Collections.addAll(set, Arrays.toString(array));
  
        // 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: " + array);
  
        // convert the Array to Set
        Set<String> set = convertArrayToSet(array);
  
        // Print the Set
        System.out.println("Set: " + set);
    }
}


Output:

Array: [Geeks, forGeeks, A computer Portal]
Set: [Geeks, forGeeks, A computer Portal]

Way 4: Using Java 8 Stream API: HashSet constructor can take another collection object to construct a new set containing the elements of the specified array. Algorithm:

  1. Get the Array to be converted.
  2. Convert the array to Stream
  3. Convert the Stream to Set using Collectors.toSet()
  4. Collect the formed set using collect() method
  5. Return the formed Set

Java




// Java Program to convert
// Array to Set in Java 8
  
import java.util.*;
import java.util.stream.*;
  
class GFG {
  
    // Generic function to convert array to set
    public static <T> Set<T> convertArrayToSet(T array[])
    {
        // create a set from the Array
        return Arrays.stream(array).collect(
            Collectors.toSet());
    }
  
    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);
    }
}


Output

Array: [Geeks, forGeeks, A computer Portal]
Set: [A computer Portal, Geeks, forGeeks]

Way 5: Using Guava Sets.newHashSet(): Sets.newHashSet() creates a mutable HashSet instance containing the elements of the specified array. Algorithm:

  1. Get the Array to be converted.
  2. Create an empty Set.
  3. Add the array into the Set by passing it as the parameter to the Sets.newHashSet() method.
  4. Return the formed Set.

Java




// Java Program to convert
// Array to Set in Java 8
  
import static com.google.common.collect.Sets.*;
import java.util.*;
import java.util.stream.*;
  
class GFG {
  
    // Generic function to convert array to set
    public static <T> Set<T> convertArrayToSet(T array[])
    {
        // create a set from the Array
        return Sets.newHashSet(array);
    }
  
    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);
    }
}


Output:

Array: [Geeks, forGeeks, A computer Portal]
Set: [Geeks, forGeeks, A computer Portal]

Way 6: Using Set.of() method : To use this method, we have to import the package java.util. It is introduced in java 9. This is a static factory method that is used to return the set object. This method will return the immutable set instance but we can make it a mutable set by giving it inside the constructor of HashSet. First, input the array element and declare the set object. Call the method for converting an array to set. Now, pass the array as a parameter and return the statement new Hashset<>(Set.of(arrayname)). 

Java




import java.util.*;
  
class GFG {
    public static <T> Set<T> convertArrayToSet(T array[])
    {
        // create a set from the array
        return new HashSet<>(Set.of(array));
    }
    
    public static void main(String args[])
    {
        // create an Array
        String array[] = { "neveropen", "forneveropen"
                                    "learning","platform" };
    
        // printing the Array
        System.out.println("Array: " + Arrays.toString(array));
    
        // declare the set object and call the function for conversion
        Set<String>
            set = convertArrayToSet(array);
    
        // print the Set
        System.out.println("Set: " + set);
    }
}


Output

Array: [neveropen, forneveropen, learning, platform]
Set: [neveropen, forneveropen, learning, platform]

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments