Program to convert Array to Set in Java
Last Updated :
19 Apr, 2023
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:
- Get the Array to be converted.
- Create an empty Set
- Iterate through the items in the Array.
- For each item, add it to the Set
- Return the formed Set
Example:
Java
import java.util.*;
import java.util.stream.*;
class GFG {
public static <T> Set<T> convertArrayToSet(T array[])
{
Set<T> set = new HashSet<>();
for (T t : array) {
set.add(t);
}
return set;
}
public static void main(String args[])
{
String array[]
= { "Geeks" , "forGeeks" , "A Computer Portal" };
System.out.println( "Array: "
+ Arrays.toString(array));
Set<String> set = convertArrayToSet(array);
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:
- Get the Array to be converted.
- Create the Set by passing the Array as parameter in the constructor of the Set with the help of Arrays.asList() method
- Return the formed Set
Example
Java
import java.util.*;
import java.util.stream.*;
class GFG {
public static <T> Set<T> convertArrayToSet(T array[])
{
Set<T> set = new HashSet<>(Arrays.asList(array));
return set;
}
public static void main(String args[])
{
String array[]
= { "Geeks" , "forGeeks" , "A computer Portal" };
System.out.println( "Array: "
+ Arrays.toString(array));
Set<String> set = convertArrayToSet(array);
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:
- Get the Array to be converted.
- Create an empty Set.
- Add the array into the Set by passing it as the parameter to the Collections.addAll() method.
- Return the formed Set
Java
import java.util.*;
import java.util.stream.*;
class GFG {
public static <T> Set<T> convertArrayToSet(T array[])
{
Set<T> set = new HashSet<>();
Collections.addAll(set, Arrays.toString(array));
return set;
}
public static void main(String args[])
{
String array[]
= { "Geeks" , "forGeeks" , "A computer Portal" };
System.out.println( "Array: " + array);
Set<String> set = convertArrayToSet(array);
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:
- Get the Array to be converted.
- Convert the array to Stream
- Convert the Stream to Set using Collectors.toSet()
- Collect the formed set using collect() method
- Return the formed Set
Java
import java.util.*;
import java.util.stream.*;
class GFG {
public static <T> Set<T> convertArrayToSet(T array[])
{
return Arrays.stream(array).collect(
Collectors.toSet());
}
public static void main(String args[])
{
String array[]
= { "Geeks" , "forGeeks" , "A computer Portal" };
System.out.println( "Array: "
+ Arrays.toString(array));
Set<String> set = convertArrayToSet(array);
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:
- Get the Array to be converted.
- Create an empty Set.
- Add the array into the Set by passing it as the parameter to the Sets.newHashSet() method.
- Return the formed Set.
Java
import static com.google.common.collect.Sets.*;
import java.util.*;
import java.util.stream.*;
class GFG {
public static <T> Set<T> convertArrayToSet(T array[])
{
return Sets.newHashSet(array);
}
public static void main(String args[])
{
String array[] = { "Geeks" , "forGeeks" ,
"A computer Portal" };
System.out.println( "Array: " + Arrays.toString(array));
Set<String>
set = convertArrayToSet(array);
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[])
{
return new HashSet<>(Set.of(array));
}
public static void main(String args[])
{
String array[] = { "geeks" , "forgeeks" ,
"learning" , "platform" };
System.out.println( "Array: " + Arrays.toString(array));
Set<String>
set = convertArrayToSet(array);
System.out.println( "Set: " + set);
}
}
|
Output
Array: [geeks, forgeeks, learning, platform]
Set: [geeks, forgeeks, learning, platform]
Similar Reads
Set in Java
The Set Interface is present in java.util package and extends the Collection interface. It is an unordered collection of objects in which duplicate values cannot be stored. It is an interface that implements the mathematical set. This interface adds a feature that restricts the insertion of duplicat
14 min read
AbstractSet Class in Java
In Java, the AbstractSet class is part of the Java Collections Framework. It provides a Skeleton implementation of the set interface, which is a collection that does not allow duplicate elements. This class is abstract, meaning it cannot be instantiated directly, but it can be extended to create a c
9 min read
EnumSet in Java
In Java, the EnumSet is a specialized set implementation for use with enum types. It is a part of java.util package and provides a highly optimized set for storing enum constants. The EnumSet is one of the specialized implementations of the Set interface for use with the enumeration type. It extends
9 min read
Java HashSet
HashSet in Java implements the Set interface of Collections Framework. It is used to store the unique elements and it doesn't maintain any specific order of elements. Can store the Null values.Uses HashMap (implementation of hash table data structure) internally.Also implements Serializable and Clon
12 min read
TreeSet in Java
TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree(red - black tree) for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equ
13 min read
ConcurrentSkipListSet in Java
In Java, the ConcurrentSkipListSet is the part of the java.util.concurrent package and provides a scalable, thread-safe alternative to TreeSet. It is a sorted set that lets multiple threads safely access and modify the set at the same time without causing issues. It is thread-safe.Elements are in so
7 min read
CopyOnWriteArraySet in Java
In Java, the CopyOnWriteArraySet is the part of the java.util.concurrent package and is used to handle thread-safe operations in multi-threaded environments. It is ideal when the set is frequently read but infrequently modified. The set ensures safe access for multiple threads, as it creates a new c
6 min read
Java LinkedHashSet
LinkedHashSet in Java implements the Set interface of the Collection Framework. It combines the functionality of a HashSet with a LinkedList to maintain the insertion order of elements. Stores unique elements only.Maintains insertion order.Provides faster iteration compared to HashSet.Allows null el
8 min read
Convert HashSet to TreeSet in Java
Hashset: Hashset in Java is generally used for operations like search, insert and delete. It takes constant time for these operations on average. HashSet is faster than TreeSet. HashSet is Implemented using a hash table. TreeSet: TreeSet in Java takes O(log n) for search, insert and delete which is
3 min read
Difference and similarities between HashSet, LinkedHashSet and TreeSet in Java
In this article, we will learn, the difference between HashSet vs LinkedHashSet and TreeSet And similarities between LinkedHashSet and TreeSet. HashSet, LinkedHashSet, and TreeSet all implement the Set interface. So we have tried to list out the differences and similarities between HashSet, LinkedHa
6 min read