Convert Array to HashSet in Java
The Single Data structure cannot be able to fulfill the requirements of the programmers that’s why there are a lot of inbuilt Data-Structures in Programming languages.
Arrays are the most commonly used Data-Structure in most programming languages. The advantage of this Data-Structure is O(1) accessing the elements of the Arrays with the help of indexing but the most common disadvantages are we cannot change the size of the array after creating and the deletion of the elements is a complicated process in Arrays.
Sets: In Java, Any group of individual objects which are represented as a single unit is known as the collection of the objects. In Java, a separate framework named the “Collection Framework” has been defined in JDK 1.2 which holds all the collection classes and interface. Sets are classified into two parts sorted set and unsorted set both have advantage and disadvantage. Sorted Set i.e TreeSet sort its unique elements but the time-complexity of TreeSet is O(N log N) but unsorted Sets such as HashSet and LinkedSet do change the order of the elements but the difference between the HashSet and LinkedSet is Random Order of its elements.
Input : Array: [1, 2, 3, 4, 5, 6] Output: Set: [1, 2, 3, 4, 5, 6] Input : Array: [a, b, c, d] Output: Set: [a, b, c, d]
Approach: Brute Force or Naive Method
Create an empty set (HashSet if unsorted elements require) Iterate the elements of the array and add one by one to the set.
1 2 3 4 5 6
Using Java 8 Stream API: HashSet constructor can take another collection object to construct a new set containing the elements of the specified array.
- Get the Array to be converted.
- Convert the array to Stream
- Convert the Stream to Set using Collectors.toSet()
- Collect the formed set using the collect() method
- Return the formed Set.
Array: [Geeks, forGeeks, A computer Portal] Set: [A computer Portal, Geeks, forGeeks]
Please Login to comment...